Skip to content

Python check if string contains substring from list | Example code

  • by

Use any() function to check if a list contains a substring in Python. The any(iterable) with iterable as a for-loop that checks if any element in the list contains the substring and returns the Boolean value.

Python example checks if the string contains a substring from the list

Simple example code. A list contains a substring if any element in the list contains that substring. For example, the list contains "AC" because "AC" is a substring of "BAC".

lst = ["ABC", "BAC", "CAB"]
str1 = "AC"

res = any(str1 in string for string in lst)

print(res)

Output:

Python check if string contains substring from list

Another example

Use a list comprehension, this way construct a new list containing each element that contains the substring.

lst = ["ABC", "BAC", "CAB"]
str1 = "AC"

res = [string for string in lst if str1 in string]

print(res)

Output: [‘BAC’]

Do comment if you have any doubts or suggestions on this Python string tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading