0 votes
1 view
in Python by (30.9k points)

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'?

1 Answer

0 votes
by (73.5k points)

We have several methods to get the items associated with abc some of the important is as follows:-

To get all the items containing abc you can use the list-comprehension below is the piece of code that illustrates how we do that:-

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

matching = [s for s in some_list if "abc" in s]

image

If you want to know more about the list-comprehension you can visit the following website:-

https://intellipaat.com/tutorial/python-tutorial/python-lists/

Another thing you can use the filter method to get the items associated with abc:-

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

print filter(lambda x: 'abc' in x, my_list)

image

...