Python check if any part of string in list
<p>I have a list containing synonyms for the word 'Good' (this list here is shortened)</p>

<pre><code>good_synonym = ['Good','good','Well','well']
</code></pre>

<p>And the program asks how the user is feeling</p>

<pre><code>print = 'Hello, ' + name + ', How are you?'
status = raw_input('')
</code></pre>

<p>But sometimes, the user may respond to the question with "I am good" (or similar)</p>

<p>If the answer contains a word in the good synonym list, I want the program to reply</p>

<pre><code>if status contains a word in good_synonym:
    print ('That is good')
else:
    print ('That is not so good')
</code></pre>

<h1>note that the first line is not real python language</h1>

<p>But I don't know which phrase to use to do the action.</p>

<p>Instead of a list with mixed-case words, use <a href="https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset" rel="nofollow"><em>set</em> objects</a>; sets make membership testing and intersection testing much easier. Store <em>lowercase text</em> only, and simply lowercase the input string:</p>

<pre><code>good_synonym = {'good', 'well'}
# good_synonym = set(['good', 'well'])  # Python 2.6
</code></pre>

<p>Now test if the input string, lowercased and split on whitespace, is a <a href="https://en.wikipedia.org/wiki/Disjoint_sets" rel="nofollow"><em>disjoint set</em></a> with <a href="https://docs.python.org/3/library/stdtypes.html#set.isdisjoint" rel="nofollow"><code>set.isdisjoint()</code></a>. If it is not a disjoint set, there is overlap between the two sets and that means at least <code>'good'</code> or <code>'well'</code> is present:</p>

<pre><code>if not good_synonym.isdisjoint(status.lower().split()):
    print ('That is good')
else:
    print ('That is not so good')
</code></pre>

<p>Testing if a set is disjoint is efficient; it only has to test words up to the first one that is in the <code>good_synonym</code> set to return <code>False</code> quickly. You could calculate the intersection instead, but that would always test <em>all</em> words in the status to build a new set object.</p>

<p>Other solutions you may have seen, use the <a href="https://docs.python.org/3/library/functions.html#any" rel="nofollow"><code>any()</code> function</a>; given a <a href="https://docs.python.org/3/tutorial/classes.html#generator-expressions" rel="nofollow">generator expression</a> it too can be efficient as it would return <code>True</code> early if any of the outputs is true:</p>

<pre><code>if any(word in good_synonym for word in status.lower().split()):
</code></pre>

<p>This, however, does all the looping and testing in Python code, while <code>set.isdisjoint()</code> is implemented entirely in C code.</p>

python