Search code examples
pythonif-statement

Determining if a string contains a word


In Python, what is the syntax for a statement that, given the following context:

words = 'blue yellow'

would be an if statement that checks to see if words contains the word "blue"? I.e.,

if words ??? 'blue':
    print 'yes'
elif words ??? 'blue':
    print 'no'

In English, "If words contain blue, then say yes. Otherwise, print no."


Solution

  • words = 'blue yellow'
    
    if 'blue' in words:
        print 'yes'
    else:
        print 'no'
    

    Also nightly blues would contain blue, but not as a whole word. If this is not what you want, split the wordlist:

    if 'blue' in words.split():
        …