Python只替换字符串中的精确单词

2024-10-06 20:35:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我只想替换一个字符串中的特定单词。然而,其他一些词里面有这个词,但我不希望它们被改变

例如,对于下面的字符串,我只想用z字符串中的y替换x。怎么做

x = "the"
y = "a"
z = "This is the thermometer"

Tags: the字符串isthis单词thermometer
2条回答

在您的情况下,可以使用re.sub(x, y, z)。 有关详细信息,请阅读文档here

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)

相关问题 更多 >