Python-仅替换字符串[duplicate]中的确切单词

问题描述 投票:-2回答:2

我只想替换一个字符串中的特定单词。但是,其他一些单词中也包含该单词,但我不希望更改它们。

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

x = "the"
y = "a"
z = "This is the thermometer"
python regex
2个回答
0
投票
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)

0
投票

根据您的情况,您可以使用re.sub(x, y, z)。您可以阅读文档here以获取更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.