SandyBr SandyBr - 11 months ago 56
Python Question

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
. How can I do that?

if 'abc' in my_list:

would check if
exists in the list but it is a part of
does not exist on its own. So how can I get all items that contain


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]