【发布时间】:2019-10-29 05:13:19
【问题描述】:
我有一个函数,我使用正则表达式替换句子中的单词。
我的功能如下:
def replaceName(text, name):
newText = re.sub(r"\bname\b", "visitor", text)
return str(newText)
举例说明:
text = "The sun is shining"
name = "sun"
print(re.sub((r"\bsun\b", "visitor", "The sun is shining"))
>>> "The visitor is shining"
但是:
replaceName(text,name)
>>> "The sun is shining"
我认为这不起作用,因为我使用的是字符串的名称(在本例中为名称)而不是字符串本身。谁知道我该怎么做才能使这个功能起作用?
我考虑过:
- Using variable for re.sub, 然而,尽管名称相似,但它是一个不同的问题。
- Python use variable in re.sub,但这只是日期和时间。
【问题讨论】:
-
re.sub(r"\b{}\b".format(name), "visitor", text)或re.sub(rf"\b{name}\b", "visitor", text)在 Python 3.7+ 中。re.escape和其他调整也应该考虑。
标签: python regex function replace