Python: How to check a string for substrings from a list?

Question:

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?

Asked By: user1045620

||

Answers:

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.

Answered By: Sven Marnach
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.