How to check if a string is a substring of items in a list of strings?
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]
Just throwing this out there: if you happen to need to match against more than one string, for example abc
and def
, you can combine two comprehensions as follows:
matchers = ['abc','def']
matching = [s for s in my_list if any(xs in s for xs in matchers)]
Output:
['abc-123', 'def-456', 'abc-456']
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.