I want to replace multiple characters in a word that only contains dots. For example. I have 4 dots, I have 2 index numbers in a list and a letter.
word = '....'
list = [2, 3]
letter = 'E'
I want to replace the 3rd and 4th (so index 2 and 3) dots in the word with the letter 'E'.
Is there a way to do this? if so how would I do this? I have tried. Replace and other methods but none seem to work.
2 Answers 2
Strings are immutable in python. You can't change them. You have to create a new string with the contents you want.
In this example I'm using enumerate to number each individual char in the word, and then checking the list of indexes to decide whether to include the original char or the new letter in the new generated word. Then join everything.
new_word = ''.join(letter if n in list else ch for n, ch in enumerate(word))
Comments
You can try this:
word = '....'
list = [2, 3]
letter = 'E'
word = ''.join(a if i not in list else letter for i, a in enumerate(word))
Output:
'..EE'
2 Comments
word and store the current iteration index. Then, the code checks if the index exists in list. If so, letter is stored in the expression. If not, the current character from word is contained.
list()(at least locally)!