Python - Check If Word Is In A String
I'm working with Python v2, and I'm trying to find out if you can tell if a word is in a string.
I have found some information about identifying if the word is in the string - using .find, but is there a way to do an IF statement. I would like to have something like the following:
if string.find(word):
print("success")
Thanks for any help.
What is wrong with:
if word in mystring:
print('success')
if 'seek' in 'those who seek shall find':
print('Success!')
but keep in mind that this matches a sequence of characters, not necessarily a whole word - for example, 'word' in 'swordsmith'
is True. If you only want to match whole words, you ought to use regular expressions:
import re
def findWholeWord(w):
return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search
findWholeWord('seek')('those who seek shall find') # -> <match object>
findWholeWord('word')('swordsmith') # -> None