Summary: In this tutorial, we will learn different ways to check for multiple substrings in another string in Python. Return True if the string contains any of the given substrings.

Method 1: Using any() with for loop to Check for Substrings

In this method, we iterate through the list of substrings and check using the in operator if it exists in another string.

We append the boolean results to a list and pass it to any() function to return True or False indicating whether any of the sub-strings are present in the string.

The any() function in Python accepts an iterable (such as List, Dictionary, Tuple, etc) as a parameter and returns True if any of the elements in the iterable is True.

substrings = ['python', 'python3', 'programming']
string = 'Learn programming at pencilprogrammer.com'

result_list = []
for x in substrings:
    # append True/False for substring x
    result_list.append(x in string)
 
#call any() with boolean results list
print(any(result_list))

Output: True

One drawback of this method is that it is case-sensitive. If a substring is present in the main string, but the case does not match, it will return false result.

We can overcome this by changing the strings to the same case (e.g lower), inside of the loop body:

substrings = ['mY', 'naME', 'is', 'KuMAR']
string = 'Author name: Adarsh Kumar'

result_list = []
for x in substrings:
    # append True/False for substring x
    result_list.append(x.lower() in string.lower())
 
#call any() with boolean results list
print(any(result_list))

Alternatively, we can check for substring using the regular expression as discussed below.

Method 2: Using any() with regular expression (re)

Using regular expressions, we can easily check multiple substrings in a single-line statement.

We use the findall() method of the re module to get all the matches as a list of strings and pass it to any() method to get the result in True or False.

import re

string = 'Python is good for Machine Learning and Data-Science'

"""
pass substrings separated by | as 1st argument
and main string value as 2nd argument.
Additionally, we can pass re.IGNORECASE paramter as
3rd argument to make matching case-insensitive.
"""
match_list = re.findall(r'python|machine|good', string, re.IGNORECASE)

print(any(match_list))

Output: True

This is one of the fastest method to check whether a string contains any of the given multiple substrings in Python.

Post author avatar

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.

Leave a Reply