替换python中的特定单词

Sih*_*ang 1 python replace

如果我有一个字符串“this is”,并且我想将“is”替换为“was”。当我使用时replace ("is", "was"),我得到了“thwas was”,但我期待的是“this was”,有什么解决办法吗?

Dao*_*Wen 6

您需要做一些比常规字符串替换更复杂的事情。我建议使用正则表达式(re模块),并使用\b转义序列匹配单词边界

import re
re.sub(r"\bis\b", "was", "This is the best island!")
Run Code Online (Sandbox Code Playgroud)

结果: 'This was the best island!'

通过使用模式r"\bis\b"而不仅仅是"is",您可以确保仅在“is”作为独立单词出现时才匹配它(即在原始字符串中没有数字、字母或下划线字符与其直接相邻)。

以下是一些匹配和不匹配的示例:

re.sub(r"\bis\b", "was", "is? is_number? is, isn't 3is is, ,is, is. hyphen-is. &is")
Run Code Online (Sandbox Code Playgroud)

结果: "was? is_number? was, isn't 3is was, ,was, was. hyphen-was. &was"