Python: 子字符串搜索

2 投票
2 回答
953 浏览
提问于 2025-04-17 03:35

我想在一个字符串中搜索完整的单词,但不知道该怎么做。

str1 = 'this is'
str2 ='I think this isnt right'
str1 in str2

这个方法给我返回了 True,但我希望它返回 False。我该怎么做呢?谢谢。

我试过 str2.find(str1)re.search(str1,str2),但是没有得到空值或者 False 的结果。

请帮帮我。谢谢。

2 个回答

1

还有一种方法是使用集合,不需要正则表达式:

set(['this', 'is']).issubset(set('I think this isnt right'.split(' ')))

如果字符串非常长,或者你需要不断检查某些单词是否在集合中,这种方法可能会更高效。例如:

>>> words = set('I think this isnt right'.split(' '))
>>> words
set(['I', 'this', 'isnt', 'right', 'think'])
>>> 'this' in words
True
>>> 'is' in words
False
3

在正则表达式中,使用 \b 这个符号可以帮助你找到单词的边界。

re.search(r'\bthis is\b', 'I think this isnt right')

撰写回答