Python - Check If Word Is In A String


Question

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.

1
157
9/1/2013 6:56:29 PM

Accepted Answer

What is wrong with:

if word in mystring: 
   print 'success'
316
3/16/2011 1:13:09 AM

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon