Skip to content
Advertisement

Check if multiple strings exist in another string

How can I check if any of the strings in an array exists in another string?

For example:

a = ['a', 'b', 'c']
s = "a123"
if a in s:
    print("some of the strings found in s")
else:
    print("no strings found in s")

How can I replace the if a in s: line to get the appropriate result?

Advertisement

Answer

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.

Advertisement