Skip to content

Python check if string contains substring from list

  • by

There are many ways to check if the string contains a substring from the list in Python. You can use any() function or filter function or for loop for it.

If you just need to know if ‘substring’ is in one of the items, this is the shortest way:

if 'abc' in str(my_list):

Python checks if the string contains a substring from the list

Simple example code checks for the presence of a substring in a list of strings. Using the list comprehension to check for the list and also with string elements if find a match, and return true, if we find one and false is not using the conditional statements.

my_lst = ['hello', 'this', 'is', 'a', 'testello']

query = 'ello'
out = [query in e for e in my_lst]

print(out)

Output:

Python check if string contains substring from list

for a numpy array:

my_array = np.array(['hello', 'this', 'is', 'a', 'testello'])

out = np.core.defchararray.find(my_array, query)>0
# array([ True, False, False, False,  True])

Using if any

xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']

if any("abc" in s for s in xs):
    ...

Use filter to get all the elements that have 'abc':

xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
res = list(filter(lambda x: 'abc' in x, xs))

print(res)

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

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