Finding Strings with Given Substring in List - Python
The task of finding strings with a given substring in a list in Python involves checking whether a specific substring exists within any of the strings in a list. The goal is to efficiently determine if the desired substring is present in any of the elements of the list. For example, given a list a = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms'], the task would be to check if a substring like 'Geek' exists.
Using filter
filter() is the efficient built-in method that allows us to filter elements in an iterable based on a condition. When combined with a lambda function, it becomes an elegant way to find strings containing a specific substring.
a = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
b = 'Geek' # Substring
res = list(filter(lambda x: b in x, a))
print(res)
Output
['GeeksforGeeks', 'Geeky']
Explanation: filter() check if the substring b is in each string of the list a, returning an iterator of matching strings, which is then converted to a list and stored in res.
Using list comprehension
List comprehension is a concise way to filter and create a new list by applying a condition to each element. It is a popular method for its readability and ease of use.
a = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
b = 'Geek' # Substring
res = [i for i in a if b in i]
print(res)
Output
['GeeksforGeeks', 'Geeky']
Explanation: list comprehension iterate through a, adding strings that contain the substring b to the list res.
Using re.findall()
re module provides powerful string matching tools. re.findall() can be used to find all non-overlapping matches of a substring or pattern in a string. While more complex than the other methods, it is flexible and can be used for more advanced matching needs.
import re
a = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
b = 'Geek' # Substring
res = [i for i in a if re.findall(b, i)]
print(res)
Output
['GeeksforGeeks', 'Geeky']
Explanation :re.findall() checks for occurrences of the substring b in each string of a. If a match is found, the string is included in the list res.
Using any()
any() checks if any element in an iterable is True. When combined with a generator expression, it can be used to find if a substring exists in any string in the list. While it’s less common for this particular task, it can still be useful in certain scenario .
a = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
b = 'Geek' #Substring
res = [i for i in a if any(b in part for part in [i])]
print(res)
Output
['GeeksforGeeks', 'Geeky']
Explanation: any()
checks if the substring b
is present in the string
i
from the list a
. If found, the string is added to the result list res
.