Python: Find A Word Within A String
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 fo
Solution 1:
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
Solution 2:
Use regex's word boundary also works
import re
if re.findall(r'\bis\b', str1):
print str1
Post a Comment for "Python: Find A Word Within A String"