How can I check if any of the strings in an array exists in another string?
Like:
a = ['a', 'b', 'c']
str = "a123"
if a in str:
print "some of the strings found in str"
else:
print "no strings found in str"
That code doesn't work, it's just to show what I want to achieve.
any()
is by far the best approach if all you want isTrue
orFalse
, but if you want to know specifically which string/strings match, you can use a couple things.If you want the first match (with
False
as a default):If you want to get all matches (including duplicates):
If you want to get all non-duplicate matches (disregarding order):
If you want to get all non-duplicate matches in the right order:
You should be careful if the strings in
a
orstr
gets longer. The straightforward solutions take O(S*(A^2)), whereS
is the length ofstr
and A is the sum of the lenghts of all strings ina
. For a faster solution, look at Aho-Corasick algorithm for string matching, which runs in linear time O(S+A).I would use this kind of function for speed:
jbernadas already mentioned the Aho-Corasick-Algorithm in order to reduce complexity.
Here is one way to use it in Python:
Download aho_corasick.py from here
Put it in the same directory as your main Python file and name it
aho_corasick.py
Try the alrorithm with the following code:
Note that the search is case-sensitive
Just to add some diversity with
regex
:or if your list is too long -
any(re.findall(r'|'.join(a), str, re.IGNORECASE))