我只想替换一个字符串中的特定单词。但是,其他一些单词中也包含该单词,但我不希望更改它们。
例如,对于下面的字符串,我只想将x
字符串中的y
替换为z
。该怎么做?
x = "the"
y = "a"
z = "This is the thermometer"
import re
pattern=r'\bthe\b' # \b - start and end of the word
repl='a'
string = 'This is the thermometer'
string=re.sub(pattern, repl, string)
根据您的情况,您可以使用re.sub(x, y, z)
。您可以阅读文档here以获取更多信息。