Álvaro Álvaro - 9 months ago 26
Python Question

Check if substring is in a list of strings in python

I have found some answers to this question before, but they seem to be obsolete for the current Python versions (or at least they don't work for me).

I want to check if a substring is contained in a list of strings. I only need the boolean result.

I found this solution:

word_to_check = 'or'
wordlist = ['yellow','orange','red']

result = any(word_to_check in word for word in worldlist)

From this code I would expect to get a
value. If the word was "der", then the output should be

However, the result is a generator function, and I can't find a way to get the

Any idea?


You can import any from __builtin__ in case it was replaced by some other any:

>>> from  __builtin__ import any as b_any
>>> lis= ['yellow', 'orange', 'red']
>>> word = "or"
>>> b_any(word in x for x in lis)

Noe that in Python 3 __builtin__ has been renamed to builtins.