2

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
  • Sidenote: Don't call things "list" in python, you will overwrite the list constructor list() (at least locally)!
    – RunOrVeith
    Commented Nov 30, 2017 at 17:45
  • what have you tryed?
    – Shapi
    Commented Nov 30, 2017 at 17:49

2 Answers 2

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

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
  • Could you explain to me how this works? so i can apply it in other circumstances.
    – Bart S.
    Commented Dec 1, 2017 at 8:22
  • @BartS. this solution is using list comprehension to iterate over 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.
    – Ajax1234
    Commented Dec 1, 2017 at 14:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.