Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 350
user1045620 Avatar asked Nov 14 '11 13:11

user1045620


People also ask

How do you check for repeated substrings in Python?

(1) First generate the possible sub-strings you want to search in each string. Is there a min or max length? Build a list or set of sub-strings from the input string. (2) Once you have the sub-strings to search for, try to identify the unique locations within the input string where the substrings appear.

How do you check if a string contains a substring from a list of substrings?

Using String.contains() method for each substring. You can terminate the loop on the first match of the substring, or create a utility function that returns true if the specified string contains any of the substrings from the specified list.

How do you test if a string contains one of the substrings in a list in pandas?

To test if a string contains one of the substrings in a list in Python Pandas, we can use the str. contains method with a regex pattern to find all the matches.


1 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.

like image 55
Sven Marnach Avatar answered Oct 11 '22 08:10

Sven Marnach