13

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."

Mattie
  • 20,280
  • 7
  • 36
  • 54
John Doe Smith
  • 165
  • 1
  • 1
  • 8

4 Answers4

23
words = 'blue yellow'

if 'blue' in words:
    print 'yes'
else:
    print 'no'

Edit

I just realized that 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():
    …
Mattie
  • 20,280
  • 7
  • 36
  • 54
salezica
  • 74,081
  • 25
  • 105
  • 166
6

You can use in or do explicit checks:

if 'blue ' in words:
    print 'yes'

or

if words.startswith('blue '):
    print 'yes'

Edit: Those 2 will only work if the sentence doesnt end with 'blue'. To check for that, you can do what one of the previous answers suggested

if 'blue' in words.split():
    print 'yes'
Kartik
  • 9,463
  • 9
  • 48
  • 52
6

You can also use regex:

\bblue\b will return True only if it can find the exact word 'blue', otherwise False.

In [24]: import re

In [25]: strs='blue yellow'

In [26]: bool(re.search(r'\bblue\b',strs))
Out[26]: True

In [27]: strs="nightly blues"

In [28]: bool(re.search(r'\bblue\b',strs))
Out[28]: False
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
2

The easiest way to do this is probably the following:

words = set('blue yellow'.split())
if 'blue' in words:
    print 'yes'
else:
    print 'no'

If your words list is really huge, you'll get a speed increase by wrapping words.split() in set as testing set membership is more computationally efficient than testing list membership.

martega
  • 2,103
  • 2
  • 21
  • 33
  • 1
    Creation of set is an `O(N)` operation in itself, so this will help only if OP wants to check for membership multiple times on the same list and the list is huge. – Ashwini Chaudhary Mar 13 '13 at 01:09