I just started learning Python and trying to write a code to replace all instances of a letter in a given string. I'm using comprehension and the code below seems to work, but based on my understanding, this shouldn't have worked. It should have just replaced one of the letters, not all. Please see the code below. I thought it would only replace the first letter "C", but it did replace both "C"s. How?
Thanks!
'''
word_before = 'ABCABCDDEEF'
letter_id = 2
letter_to_replace = word[letter_id]
word_after = [word_before.replace(x, '_') for i, x in enumerate(word_before) if i==letter_id]
word_after = str(word_after)
print(word_after)
'''
What your code is doing: "if i == 2, give whole_word.replace('C', '_'), else does nothing"
What you want it to do: if i == 2, give "_", else give original character (Only replaces the first letter)
word_before = 'ABCABCDDEEF'
letter_id = 2
letter_to_replace = word[letter_id] # This is not used, since you're checking via index not letter
word_after = ['_' if i == letter_id else x for i, x in enumerate(word_before)] # Correct expression
word_after = ''.join(word_after) # Combines ['A', 'B'] -> 'AB' (list -> string)
print(word_after) # AB_ABCDDEEF