【发布时间】:2011-11-30 01:39:38
【问题描述】:
我正在尝试在字符串中搜索整个单词,但不知道该怎么做。
str1 = 'this is'
str2 ='I think this isnt right'
str1 in str2
给我True,但我希望它返回False。我该怎么做呢?谢谢。
我尝试了str2.find(str1), re.search(str1,str2),,但我没有让他们不返回任何内容或返回 False。
请帮忙。谢谢。
【问题讨论】:
我正在尝试在字符串中搜索整个单词,但不知道该怎么做。
str1 = 'this is'
str2 ='I think this isnt right'
str1 in str2
给我True,但我希望它返回False。我该怎么做呢?谢谢。
我尝试了str2.find(str1), re.search(str1,str2),,但我没有让他们不返回任何内容或返回 False。
请帮忙。谢谢。
【问题讨论】:
在正则表达式中使用\b 实体来匹配单词边界。
re.search(r'\bthis is\b', 'I think this isnt right')
【讨论】:
\b 在r'\bthis is\b' 的开头和结尾。这些是单词边界。
不带正则表达式使用sets 的另一种方式:
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
【讨论】:
set(['this', 'is']).issubset(set('I think this thing is wrong'.split(' ')))。