Python 列表理解 - 替换字符串中的多个字母
Python List Comprehension - Replacing Multiple Letters in a String
我刚开始学习 Python 并尝试编写代码来替换给定字符串中字母的所有实例。我正在使用理解,下面的代码似乎有效,但根据我的理解,这不应该有效。它应该只是替换了其中一个字母,而不是全部。请看下面的代码。我以为它只会替换第一个字母 "C",但它确实替换了两个 "C"。怎么样?
谢谢!
'''
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)
'''
您的代码在做什么:"if i == 2, give whole_word.replace('C', '_'), else does nothing"
你想要它做什么:如果 i == 2,给出“_”,否则给出原始字符(只替换第一个字母)
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
我刚开始学习 Python 并尝试编写代码来替换给定字符串中字母的所有实例。我正在使用理解,下面的代码似乎有效,但根据我的理解,这不应该有效。它应该只是替换了其中一个字母,而不是全部。请看下面的代码。我以为它只会替换第一个字母 "C",但它确实替换了两个 "C"。怎么样?
谢谢!
'''
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)
'''
您的代码在做什么:"if i == 2, give whole_word.replace('C', '_'), else does nothing"
你想要它做什么:如果 i == 2,给出“_”,否则给出原始字符(只替换第一个字母)
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