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'
?
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.
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.
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With