不要在循环中使用str.replace
.这通常不会达到预期效果,因为它不适用于单词,但适用于所有匹配项.
取而代之的是,split
个单词,替换为match和join
:
l = ['Twinkle Twinkle', 'How I wonder']
def sub(old: str, new: str, words: list):
words[:] = [' '.join(new if w==old else w for w in x.split()) for x in words]
sub('I', 'ASD', l)
yields :['Twinkle Twinkle', 'How ASD wonder']
或者使用带有单词边界的正则表达式:
import re
def sub(old, new, words):
words[:] = [re.sub(fr'\b{re.escape(old)}\b', new, w) for w in words]
l = ['Twinkle Twinkle', 'How I wonder']
sub('I', 'ASD', l)
# ['Twinkle Twinkle', 'How ASD wonder']
NB. As @re-za pointed out, it might be a better practice to 100 a new list rather than mutating the input, just be aware of it