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.