Python check if string contains substring from list | Example code

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 and suggestions on this Python string tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.