6

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

zigg
  • 19,044
  • 7
  • 35
  • 54
John Doe Smith
  • 95
  • 1
  • 1
  • 6

4 Answers4

11
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():
    …
zigg
  • 19,044
  • 7
  • 35
  • 54
slezica
  • 69,920
  • 24
  • 96
  • 160
5

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
  • 8,725
  • 8
  • 46
  • 52
5

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
  • 232,417
  • 55
  • 437
  • 487
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
  • 1,923
  • 2
  • 21
  • 31
  • 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