145

How can I check a string for substrings contained in a list, like in Check if a string contains an element from a list (of strings), but in Python?

0

1 Answer 1

310

Try this test:

any(substring in string for substring in substring_list)

It will return True if any of the substrings in substring_list is contained in string.

Note that there is a Python analogue of Marc Gravell's answer in the linked question:

from itertools import imap
any(imap(string.__contains__, substring_list)) 

In Python 3, you can use map directly instead:

any(map(string.__contains__, substring_list))

Probably the above version using a generator expression is more clear though.

Sign up to request clarification or add additional context in comments.

4 Comments

@newtover: Generator expressions don't have square brackets.
is there any way to get the substring when it will return True?
@vagabond You can use next(substring for substring in substring_list if substring in string), which will return the first matching substring, or throw StopIteration if there is no match. Or use a simple loop: for substring in substring_list: if substring in string: return substring.
@SvenMarnach variable 'substring''s lifetime is DONE and unavailable in the StopIteration exception

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.