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" is a substring of
lst = ["ABC", "BAC", "CAB"] str1 = "AC" res = any(str1 in string for string in lst) print(res)
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)
Do comment if you have any doubts and suggestions on this Python string tutorial.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.