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'
?
Just throwing this out there: if you happen to need to match against more than one string, for example
abc
anddef
, you can put combine two list comprehensions as follows:Output:
Question : Give the informations of abc
If you only want to check for the presence of
abc
in any string in the list, you could tryIf you really want to get all the items containing
abc
, useThis is quite an old question, but I offer this answer because the previous answers do not cope with items in the list that are not strings (or some kind of iterable object). Such items would cause the entire list comprehension to fail with an exception.
To gracefully deal with such items in the list by skipping the non-iterable items, use the following:
then, with such a list:
you will still get the matching items (
['abc-123', 'abc-456']
)The test for iterable may not be the best. Got it from here: In Python, how do I determine if an object is iterable?