Check if multiple strings exist in another string
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Forest of Spells Looping
--
Chapters
00:00 Check If Multiple Strings Exist In Another String
00:20 Accepted Answer Score 1282
00:33 Answer 2 Score 67
00:55 Answer 3 Score 44
01:14 Answer 4 Score 119
01:50 Thank you
--
Full question
https://stackoverflow.com/questions/3389...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #arrays #string #exists
#avk47
ACCEPTED ANSWER
Score 1282
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.
ANSWER 2
Score 119
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 a_string), False)
If you want to get all matches (including duplicates):
matches = [x for x in a if x in a_string]
If you want to get all non-duplicate matches (disregarding order):
matches = {x for x in a if x in a_string}
If you want to get all non-duplicate matches in the right order:
matches = []
for x in a:
    if x in a_string and x not in matches:
        matches.append(x)
ANSWER 3
Score 67
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).
ANSWER 4
Score 44
Just to add some diversity with regex:
import re
if any(re.findall(r'a|b|c', str, re.IGNORECASE)):
    print 'possible matches thanks to regex'
else:
    print 'no matches'
or if your list is too long - any(re.findall(r'|'.join(a), str, re.IGNORECASE))