Wednesday, December 25, 2024
Google search engine
HomeLanguagesPython | Finding strings with given substring in list

Python | Finding strings with given substring in list

Method #1: Using list comprehension 

List comprehension is an elegant way to perform any particular task as it increases readability in the long run. This task can be performed using a naive method and hence can be reduced to list comprehension as well. 

Python3




# Python code to demonstrate
# to find strings with substrings
# using list comprehension
 
# Initializing list
test_list = ['Lazyroar', 'Geeky', 'Computers', 'Algorithms']
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Initializing substring
subs = 'Geek'
 
# using list comprehension
# to get string with substring
res = [i for i in test_list if subs in i]
 
# Printing result
print("All strings with given substring are : " + str(res))


Output

The original list is : ['Lazyroar', 'Geeky', 'Computers', 'Algorithms']
All strings with given substring are : ['Lazyroar', 'Geeky']

Time complexity: O(n), where n is the length of the test_list.
Auxiliary space: O(1), as only a few variables are used in the code.

Method #2: Using filter() + lambda 

This function can also perform the task of finding the strings with the help of lambda. It just filters out all the strings matching the particular substring and then adds it to a new list. 

Python3




# Python code to demonstrate
# to find strings with substrings
# using filter() + lambda
 
# Initializing list
test_list = ['Lazyroar', 'Geeky', 'Computers', 'Algorithms']
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Initializing substring
subs = 'Geek'
 
# Getting string with substring
# using filter() + lambda
res = list(filter(lambda x: subs in x, test_list))
 
# Printing the resultant string
print("All strings with given substring are : " + str(res))


Output

The original list is : ['Lazyroar', 'Geeky', 'Computers', 'Algorithms']
All strings with given substring are : ['Lazyroar', 'Geeky']

Time complexity: O(n) where n is the number of elements in the test_list. 
Auxiliary space: O(m) where m is the number of elements in the result list. 

Method #3: Using re + search() 

Regular expressions can be used to perform many task in python. To perform this particular task also, regular expressions can come handy. It finds all the matching substring using search() and returns result. 
 

Python3




# Python code to demonstrate
# to find strings with substrings
# using re + search()
 
import re
 
# Initializing list
test_list = ['Lazyroar', 'Geeky', 'Computers', 'Algorithms']
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Initializing substring
subs = 'Geek'
 
# Getting string with substring
# using re + search()
res = [x for x in test_list if re.search(subs, x)]
 
# Printing the result
print("All strings with given substring are : " + str(res))


Output

The original list is : ['Lazyroar', 'Geeky', 'Computers', 'Algorithms']
All strings with given substring are : ['Lazyroar', 'Geeky']

Time complexity: O(n * m), where n is the length of the list and m is the length of the substring. 
Auxiliary space: O(k), where k is the number of strings that contain the substring.

Method #4 : Using find() method

Python3




# Python code to demonstrate
# to find strings with substrings
 
# initializing list
test_list = ['Lazyroar', 'Geeky', 'Computers', 'Algorithms']
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing substring
subs = 'Geek'
res = []
for i in test_list:
    if i.find(subs) != -1:
        res.append(i)
 
# printing result
print("All strings with given substring are : " + str(res))


Output

The original list is : ['Lazyroar', 'Geeky', 'Computers', 'Algorithms']
All strings with given substring are : ['Lazyroar', 'Geeky']

Time complexity: O(n*m), where n is the length of the input list and m is the length of the substring to search for. The loop iterates through each element of the list and calls the find() method on each element, which has a time complexity of O(m) in the worst case.

Auxiliary space: O(k), where k is the number of elements in the result list. The result list res is created to store all the strings that contain the given substring. The maximum size of res is n, the length of the input list, if all elements contain the substring.

Method #5 : Using replace() and len() methods

Python3




# Python code to demonstrate
# to find strings with substrings
 
# initializing list
test_list = ['Lazyroar', 'Geeky', 'Computers', 'Algorithms']
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing substring
subs = 'Geek'
res = []
for i in test_list:
    x = i.replace(subs, "")
    if(len(x) != len(i)):
        res.append(i)
# printing result
print("All strings with given substring are : " + str(res))


Output

The original list is : ['Lazyroar', 'Geeky', 'Computers', 'Algorithms']
All strings with given substring are : ['Lazyroar', 'Geeky']

Method #6 : Using a try/except block and the index()

Here is an example of using a try/except block and the index() method to find strings with a given substring in a list:

Python3




# initialize the result list
res = []
test_list = ['Lazyroar', 'Geeky', 'Computers', 'Algorithms']
subs = 'Geek'
 
# iterate over the elements in the input list
for element in test_list:
    try:
        # use the index method to find the first occurrence of the substring
        index = element.index(subs)
        # if the index method does not raise an exception, it means that the substring was present in the string
        res.append(element)
    except ValueError:
        # if the index method raises a ValueError, it means that the substring was not present in the string
        pass
 
# print the result
print("All strings with given substring are : " + str(res))
 
#This code is contributed by Edula Vinay Kumar Reddy


Output

All strings with given substring are : ['Lazyroar', 'Geeky']

Time complexity: O(n) since it involves a single pass through the input list. It is a simple and efficient method for finding strings with a given substring in a list, and it allows you to handle the case where the substring is not present in the string using a try/except block.
Auxiliary Space: O(n)

Method#7: Using for loop

Here’s the step-by-step algorithm for finding strings with a given substring in a list

  1. Initialize the list of strings and the substring to search for.
  2. Initialize an empty list to store the strings that contain the substring.
  3. Loop through each string in the original list.
  4. Check if the substring is present in the current string.
  5. If the substring is present in the current string, add the string to the result list.
  6. Print the original list and the result list.

Python3




# initializing list
test_list = ['Lazyroar', 'Geeky', 'Computers', 'Algorithms']
 
# initializing substring
subs = 'Geek'
 
# initializing empty list to store result
res = []
 
# using for loop to get string with substring
for i in test_list:
    if subs in i:
        res.append(i)
 
# printing original list
print("The original list is : " + str(test_list))
 
# printing result
print("All strings with given substring are : " + str(res))
#This code is contributed by Vinay pinjala.


Output

The original list is : ['Lazyroar', 'Geeky', 'Computers', 'Algorithms']
All strings with given substring are : ['Lazyroar', 'Geeky']

The time complexity of this algorithm is O(n*m), where n is the number of strings in the original list and m is the length of the longest string in the list. This is because in the worst case, we have to loop through every string in the list and check if the substring is present in each string, which takes O(m) time.

The space complexity of this algorithm is O(k), where k is the number of strings in the original list that contain the substring. This is because we are storing the result strings in a list, which can have a maximum size of k.

NumPy approach to find strings with a given substring in a list:

Algorithm:

Convert the given list to a NumPy array.
Create an empty NumPy array of the same shape as the input array to store the boolean values for the given condition.
Use the numpy.char.find() function to find the indices of the given substring in the input array.
Use the numpy.where() function to get the indices where the given condition is True.
Use the indices obtained from step 4 to extract the required elements from the input array.

Python3




import numpy as np
 
# initializing list
test_list = ['Lazyroar', 'Geeky', 'Computers', 'Algorithms']
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing substring
subs = 'Geek'
 
# convert list to numpy array
test_array = np.array(test_list)
 
# initialize output array
output_array = np.zeros_like(test_array, dtype=bool)
 
# find indices where substring is present
index_array = np.char.find(test_array, subs)
 
# set True at indices where substring is present
output_array[np.where(index_array != -1)] = True
 
# extract the required elements from the input array
res = test_array[output_array]
 
# printing result
print("All strings with given substring are : " + str(res))


Output:

The original list is : ['Lazyroar', 'Geeky', 'Computers', 'Algorithms']
All strings with given substring are : ['Lazyroar' 'Geeky']

Time Complexity: O(N*M), where n is the length of the input list and m is the length of the substring. The numpy.char.find() function has a time complexity of O(nm) in the worst case, where n is the number of elements in the input array and m is the length of the substring.
Auxiliary Space: O(n), where n is the number of elements in the input array. The numpy.char.find() function creates a temporary array of the same size as the input array to store the indices where the substring is present. 

RELATED ARTICLES

Most Popular

Recent Comments