Bart S.
Bart S.

Reputation: 39

python - Replacing multiple specific characters in a string

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.

Upvotes: 2

Views: 121

Answers (2)

Ajax1234
Ajax1234

Reputation: 71451

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'

Upvotes: 0

nosklo
nosklo

Reputation: 222792

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))

Upvotes: 2

Related Questions