111

Possible Duplicate:
Check if multiple strings exist in another string

I can't seem to find an equivalent of code that functions like this anywhere for Python:

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

Community
  • 1
  • 1
user1045620
  • 1,113
  • 2
  • 8
  • 4

1 Answers1

222

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.

Alex Fortin
  • 1,808
  • 1
  • 17
  • 27
Sven Marnach
  • 530,615
  • 113
  • 910
  • 808
  • 3
    @newtover: [Generator expressions](http://docs.python.org/tutorial/classes.html#generator-expressions) don't have square brackets. – Sven Marnach Nov 14 '11 at 17:34
  • 6
    is there any way to get the substring when it will return True? – zztczcx Apr 26 '17 at 23:50
  • 11
    @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`. – Sven Marnach May 03 '17 at 09:31
  • awesome. Python is beautiful! – Dev_Man Jul 03 '18 at 12:10