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
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
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)]
['abc-123', 'def-456', 'abc-456']
filter to get at the elements that have
'abc-123', 'def-456', 'ghi-789', 'abc-456']print filter(lambda x: 'abc' in x, lst)['abc-123', 'abc-456']lst = [
You can also use a list comprehension.
for x in lst if 'abc' in x][x
By the way, don't use the word
list as a variable name since it is already used for the