Python:动态组合的正则表达式在FindItemer中不起作用

Python:动态组合的正则表达式在FindItemer中不起作用,python,regex,Python,Regex,我想在一个句子中找到匹配的词,并动态地提供这个词。我编写了以下代码,可用于该示例: text="Algorithmic detection of misinformation and disinformation Gricean perspectives" found=re.finditer(r"\bdetection\b", text) for i in found: print("found") #this line prints exactly once 但由于我需要目标单词作为

我想在一个句子中找到匹配的词,并动态地提供这个词。我编写了以下代码,可用于该示例:

text="Algorithmic detection of misinformation and disinformation Gricean perspectives"
found=re.finditer(r"\bdetection\b", text)
for i in found:
    print("found") #this line prints exactly once
但由于我需要目标单词作为输入,而这个输入是未知的,所以我更改了如下代码,它停止了工作:

text="Algorithmic detection of misinformation and disinformation Gricean perspectives"
word="detection" #or passed by other functions etc.
found=re.finditer(r"\b"+word+"\b", text)
for i in found:
    print("found") #this line does not print in this piece of code
我应该如何更正我的代码?感谢

只需:

found=re.finditer(r"\b"+word+r"\b", text)
#         raw string here ___^

word
也需要是原始字符串吗?谢谢,它works@Ziqi:不客气,很高兴能帮上忙。请随意将答案标记为已接受,请参见:
text = "Algorithmic detection of misinformation and disinformation Gricean perspectives"
word = "detection"  # or passed by other functions etc.
pat = re.compile(fr"\b{word}\b")   # precompiled pattern
found = pat.finditer(text)
for i in found:
    print("found")