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

PythonStringListSubstring

Python Problem Overview


> Possible Duplicate:
> Check if multiple strings exist in another string

I can't seem to find an equivalent of code that functions like https://stackoverflow.com/questions/500925/to-check-if-a-string-contains-an-element-from-a-list-of-strings-is-there-a-b">this</a> anywhere for Python:

Basically, I'd like to check a string for substrings contained in a list.

Python Solutions


Solution 1 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1045620View Question on Stackoverflow
Solution 1 - PythonSven MarnachView Answer on Stackoverflow