Check if a Python list item contains a string inside another string


I have a list:

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

and want to search for items that contain the string 'abc'. How can I do that?

if 'abc' in my_list:

would check if 'abc' exists in the list but it is a part of 'abc-123' and 'abc-456', 'abc' does not exist on its own. So how can I get all items that contain 'abc' ?

10/19/2015 8:31:59 PM

Accepted Answer

If you only want to check for the presence of abc in any string in the list, you could try

some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
if any("abc" in s for s in some_list):
    # whatever

If you really want to get all the items containing abc, use

matching = [s for s in some_list if "abc" in s]
10/2/2015 8:17:45 PM

Use filter to get at the elements that have abc.

>>> lst = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
>>> print filter(lambda x: 'abc' in x, lst)
['abc-123', 'abc-456']

You can also use a list comprehension.

>>> [x for x in lst if 'abc' in x]

By the way, don't use the word list as a variable name since it is already used for the list type.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow