在 re.sub 中使用变量名

Emi*_*mil 3 python regex replace function

我有一个函数,我使用正则表达式来替换句子中的单词。

我的功能如下:

def replaceName(text, name):
    newText = re.sub(r"\bname\b", "visitor", text) 
    return str(newText)
Run Code Online (Sandbox Code Playgroud)

为了显示:

text = "The sun is shining"
name = "sun"

print(re.sub((r"\bsun\b", "visitor", "The sun is shining"))

>>> "The visitor is shining"
Run Code Online (Sandbox Code Playgroud)

然而:

replaceName(text,name)
>>> "The sun is shining"
Run Code Online (Sandbox Code Playgroud)

我认为这不起作用,因为我使用的是字符串的名称(在本例中为名称)而不是字符串本身。谁知道我能做什么才能使这个功能起作用?

我考虑过:

  1. 对 re.sub 使用变量,尽管名称相似,但它是一个不同的问题。
  2. Python 在 re.sub 中使用变量,但这只是关于日期和时间。

yat*_*atu 7

您可以在此处使用字符串格式:

def replaceName(text, name):
    newText = re.sub(r"\b{}\b".format(name), "visitor", text) 
    return str(newText)
Run Code Online (Sandbox Code Playgroud)

否则在你的情况下re.sub只是寻找完全匹配"\bname\b"


text = "The sun is shining"
name = "sun"
replaceName(text,name)
# 'The visitor is shining'
Run Code Online (Sandbox Code Playgroud)

或者对于 python 版本,3.6<您可以使用f-strings,正如@wiktor 在评论中指出的那样:

def replaceName(text, name):
    newText = re.sub(rf"\b{name}\b", "visitor", text) 
    return str(newText)
Run Code Online (Sandbox Code Playgroud)