1.test_str = 'Kobe is one of the best basketball players'
result = test_str.replace('one','on')
print(result)
Kobe is on of the best basketball players
我想要的结果是替换完整的单词,而不是单词中的一部分,只有完全匹配才能替换
Kobe is one of the best basketball players
这里没有完全的匹配不替换才对
而且也不能使用下列的方法,因为我还有其他的单词需要匹配
patt = re.compile(f'^{uk}$')
text = re.sub(patt,us,text)
你需要在你的搜索内容两侧各添加一个空格,这样就可以把它标记为是一个单词。
比如'one'改为' one '或' ' + 'one' + ' ',因为考虑到可能使用变量的情况,就需要用拼接。
有帮助请采纳,还有不懂的可以继续追问~
1例不就是完全匹配吗?怎么不能替换?
没搞懂 你为什么没成功
前面是 __old需要匹配的字符串 后边__new代表要替换为的字符串
def replace(self, __old: str, __new: str, __count: SupportsIndex = ...)