Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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():
    …

Solution 2:

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'

Solution 3:

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

Solution 4:

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.

Post a Comment for "Determining If A String Contains A Word"