Check if multiple strings exist in another string
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.
Solution 1:
You can use any
:
a_string = "A string is more than its parts!"
matches = ["more", "wholesome", "milk"]
if any(x in a_string for x in matches):
Similarly to check if all the strings from the list are found, use all
instead of any
.
Solution 2:
any()
is by far the best approach if all you want is True
or False
, 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):
match = next((x for x in a if x in str), False)
If you want to get all matches (including duplicates):
matches = [x for x in a if x in str]
If you want to get all non-duplicate matches (disregarding order):
matches = {x for x in a if x in str}
If you want to get all non-duplicate matches in the right order:
matches = []
for x in a:
if x in str and x not in matches:
matches.append(x)
Solution 3:
You should be careful if the strings in a
or str
gets longer. The straightforward solutions take O(S*(A^2)), where S
is the length of str
and A is the sum of the lenghts of all strings in a
. For a faster solution, look at Aho-Corasick algorithm for string matching, which runs in linear time O(S+A).