2

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.

2 Answers 2

3

Use the \b entity in regular expressions to match word boundaries.

re.search(r'\bthis is\b', 'I think this isnt right')
Sign up to request clarification or add additional context in comments.

6 Comments

ok. Thanks. how do I generalize this using word1 = 'this is' and line1 = 'I think this isnt right'?
Er, same way as you generalize anything else: by using variables. What are you having problems with?
I have str1 = 'this is' and str2 = 'i think this isnt right'. my syntax isnt working. re.search(str1,str2). It gives the object position. How do I make is return nothing? thanks.
@Pradeep: Notice the \b at the beginning and ending of r'\bthis is\b'. Those are word boundaries.
@StevenRumbalski, Yes, I understand. how do I pass variable instead of 'this is'? Thanks.
|
1

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

1 Comment

I believe Pradeep would want this to return false: set(['this', 'is']).issubset(set('I think this thing is wrong'.split(' '))).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.