Python: sub string search
I am trying to search for whole words with in a string and not sure how to do it.
str1 = 'this is'
str2 ='I think this isnt right'
str1 in str2
gives me True
, but I want it to return False
. 开发者_运维百科How do I do this? Thank you.
I tried str2.find(str1), re.search(str1,str2),
but I am not getting them to return nothing or a False.
Please help. thanks.
Use the \b
entity in regular expressions to match word boundaries.
re.search(r'\bthis is\b', 'I think this isnt right')
Another way using sets without a regular expression:
set(['this', 'is']).issubset(set('I think this isnt right'.split(' ')))
If the string is really long or you're going to keep evaluating if words are in the set, this could be more efficient. For example:
>>> words = set('I think this isnt right'.split(' '))
>>> words
set(['I', 'this', 'isnt', 'right', 'think'])
>>> 'this' in words
True
>>> 'is' in words
False
精彩评论