Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string is a substring of items in a list of strings?

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

like image 207
SandyBr Avatar asked Jan 30 '11 13:01

SandyBr


People also ask

How do I check if a string is substring of a list of strings?

Method #2 : Using any() The any function can be used to compute the presence of the test substring in all the strings of the list and return True if it's found in any. This is better than the above function as it doesn't explicitly take space to create new concatenated string.

How do you check if a list contains a certain string in Python?

To check if the list contains an element in Python, use the “in” operator. The “in” operator checks if the list contains a specific item or not. It can also check if the element exists on the list or not using the list.

How do you check if any element in a list is in a string?

Use the filter() Function to Get a Specific String in a Python List. The filter() function filters the given iterable with the help of a function that checks whether each element satisfies some condition or not. It returns an iterator that applies the check for each of the elements in the iterable.

How do you test if a string contains one of the substrings in a list in pandas?

To test if a string contains one of the substrings in a list in Python Pandas, we can use the str. contains method with a regex pattern to find all the matches.


1 Answers

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] 
like image 75
Sven Marnach Avatar answered Sep 29 '22 09:09

Sven Marnach