Reputation: 229
I'm trying to find a word within a string with Python.
str1 = 'This string'
if 'is' in str1:
print str1
In the above example I would want it to not print str1. While in the following example I would want it to print str2.
str2 = 'This is a string'
if 'is' in str2:
print str2
How would I go about doing this in Python?
Upvotes: 0
Views: 6401
Reputation: 12782
Use regex's word boundary also works
import re
if re.findall(r'\bis\b', str1):
print str1
Upvotes: 5
Reputation: 46593
Split the string into words and search them:
if 'is' in str1.split(): # 'is' in ['This', 'string']
print(str1) # never printed
if 'is' in str2.split(): # 'is' in ['This', 'is', 'a', 'string']
print(str2) # printed
Upvotes: 5