3

比如说,我想检查单词test是否在字符串中。通常,我只会:

if 'test' in theString

但我想确保它是实际单词,而不仅仅是字符串。例如,test在“It was detestable”中会产生误报。我可以检查以确保它包含(\s)test(\s)(之前和之后的空格),但不是“......准备测试!” 会产生假阴性。看来我唯一的其他选择是:

if ' test ' in theString or ' test.' in theString or ' test!' in theString or.....

有没有办法正确地做到这一点,比如if 'test'.asword in theString

4

1 回答 1

10
import re
if re.search(r'\btest\b', theString):
    pass

这将在test. 从文档中,\b

匹配空字符串,但只匹配单词的开头或结尾。单词被定义为字母数字或下划线字符的序列,因此单词的结尾由空格或非字母数字、非下划线字符表示。

于 2012-08-03T23:53:42.207 回答