-1
def main():
        letters = ['h', 'i', 'r', 'l', 'o', 'e', 'a', 'n', 't', 's']
        text = "A novel is a relatively long work of narrative fiction, normally written in prose form, and which is typically published as a book".lower()
        for j in text:
            if not(j in letters):
                text.replace(j, '')
        print(text)

if __name__ == '__main__':
        main()

I want to replace letter to '' in the text if it is not in my array letters but it it is not working

2 Answers2

2

Strings are immutable objects in python. So, here text.replace(j, '') only returns you a string with replaced/deleted character, but does not change the original.

1

As Vorashil Farzaliyev well said, strings are immutable objects, which basically means that you cannot edit them after they are created. The replace() function doesn't change the string in place, but it returns a new string with the replacement that you want.

Another way of getting the desired output, might be by using the join() function of the str class, passing a generator comprehension to it, with filtering purposes. This will give you a new string, which you could re-assign to the text name, if you want.

letters = ['h', 'i', 'r', 'l', 'o', 'e', 'a', 'n', 't', 's', ' ']
text = "A novel is a relatively long work of narrative fiction, normally written in prose form, and which is typically published as a book".lower()
text = "".join(letter for letter in text if letter in letters)
print(text)
# outputs: a noel is a relatiel lon or o narratie ition norall ritten in rose or an hih is tiall lishe as a oo

Please note that in order of getting that output, you need to include the space character (' ') within the letters list. Otherwise, you'd get all letters joined together.

revliscano
  • 2,227
  • 2
  • 12
  • 21