Python | Filter String with substring at specific position
Last Updated :
08 Apr, 2023
Sometimes, while working with Python string lists, we can have a problem in which we need to extract only those lists that have a specific substring at a specific position. This kind of problem can come in data processing and web development domains. Let us discuss certain ways in which this task can be performed.
Method #1: Using list comprehension + list slicing The combination of the above functionalities can be used to perform this particular task. In this, we check for substring range using list slicing, and the task of extraction list is compiled in list comprehension.
Python3
# Python3 code to demonstrate
# Filter String with substring at specific position
# using list comprehension + list slicing
# Initializing list
test_list = ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
# printing original list
print("The original list is : " + str(test_list))
# Initializing substring
sub_str = 'geeks'
# Initializing range
i, j = 0, 5
# Filter String with substring at specific position
# using list comprehension + list slicing
res = [ele for ele in test_list if ele[i: j] == sub_str]
# printing result
print("Filtered list : " + str(res))
Output : The original list is : ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
Filtered list : ['geeksforgeeks', 'geeks']
Time Complexity: O(n) where n is the total number of values in the list “test_list”.
Auxiliary Space: O(n) where n is the total number of values in the list “test_list”.
Method #2: Using filter() + lambda The combination of the above methods can be used to perform this task. In this, we filter the elements using logic compiled using lambda using filter().
Python3
# Python3 code to demonstrate
# Filter String with substring at specific position
# using filter() + lambda
# Initializing list
test_list = ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
# printing original list
print("The original list is : " + str(test_list))
# Initializing substring
sub_str = 'geeks'
# Initializing range
i, j = 0, 5
# Filter String with substring at specific position
# using filter() + lambda
res = list(filter(lambda ele: ele[i: j] == sub_str, test_list))
# printing result
print("Filtered list : " + str(res))
Output : The original list is : ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
Filtered list : ['geeksforgeeks', 'geeks']
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3 : Using find() method
Python3
# Python3 code to demonstrate
# Filter String with substring at specific position
# Initializing list
test_list = ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
# printing original list
print("The original list is : " + str(test_list))
# Initializing substring
sub_str = 'geeks'
# Initializing range
i, j = 0, 5
# Filter String with substring at specific position
res=[]
for k in test_list:
if k.find(sub_str)==i:
res.append(k)
# printing result
print ("Filtered list : " + str(res))
OutputThe original list is : ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
Filtered list : ['geeksforgeeks', 'geeks']
Time Complexity: O(n), where n is the length of the input list. This is because we’re using the built-in find() method which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.
Method 4 : Using a for loop and string slicing
step by step approach for the program:
- Initialize the list test_list with some strings.
- Print the original list using the print() function.
- Initialize a substring sub_str which we want to search for in the list of strings.
- Initialize two variables i and j which represent the range in which we want to check for the substring. In this case, we want to check if the substring exists at the start of the string, so i is 0 and j is 5 (length of sub_str).
- Create an empty list res to store the filtered strings.
- Loop through each string k in test_list.
- Check if the substring sub_str exists at the specific position using string slicing. If it does, append the string k to the res list.
- Print the filtered list using the print() function.
Python3
## Python3 code to demonstrate
# Filter String with substring at specific position
# Initializing list
test_list = ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
# printing original list
print("The original list is : " + str(test_list))
# Initializing substring
sub_str = 'geeks'
# Initializing range
i, j = 0, 5
# Filter String with substring at specific position
res=[]
for k in test_list:
if k[i:i+len(sub_str)] == sub_str:
res.append(k)
# printing result
print ("Filtered list : " + str(res))
OutputThe original list is : ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
Filtered list : ['geeksforgeeks', 'geeks']
The time complexity of this program is O(n*m), where n is the length of the test_list and m is the length of the sub_str.
The auxiliary space of this program is O(k), where k is the size of the resulting list that contains the filtered strings.
Similar Reads
Python - Filter Tuples with Strings of specific characters
Given a Tuple List, extract tuples, which have strings made up of certain characters. Input : test_list = [('gfg', 'best'), ('gfg', 'good'), ('fest', 'gfg')], char_str = 'gfestb' Output : [('gfg', 'best'), ('fest', 'gfg')] Explanation : All tuples contain characters from char_str. Input : test_list
5 min read
Python - Filter list of strings based on the substring list
The problem requires to check which strings in the main list contain any of the substrings from a given list and keep only those that match. Let us explore this problem and understand different methods to solve it.Using list comprehension with any() (Most Efficient)List comprehension is a concise an
4 min read
Python - Remove after substring in String
Removing everything after a specific substring in a string involves locating the substring and then extracting only the part of the string that precedes it. For example we are given a string s="Hello, this is a sample string" we need to remove the part of string after a particular substring includin
3 min read
Find the List elements starting with specific letter - Python
The goal is to filter the elements of a list that start with a specific letter, such as 'P'. For example, in the list ['Python', 'Java', 'C++', 'PHP'], we aim to find the elements that begin with the letter 'P', resulting in the filtered list ['Python', 'PHP']. Let's explore different approaches to
3 min read
Add Substring at Specific Index Python
In Python, String is an immutable datatype, what this means is, that there are lot many restrictions when one handles its manipulation. The problem of adding something at a position at string is not possible, without the list reconstruction. Let's discuss certain ways in which this task can be perfo
6 min read
Python - Filter Strings combination of K substrings
Given a Strings list, extract all the strings that are a combination of K substrings. Input : test_list = ["geeks4u", "allbest", "abcdef"], substr_list = ["s4u", "est", "al", "ge", "ek", "def"], K = 3 Output : ['geeks4u'] Explanation : geeks4u made up of 3 substr - ge, ek and s4u. Input : test_list
4 min read
Python - Possible Substring count from String
Given target string and argument substring, count how many substrings can be constructed using string characters, repetitions not allowed. Input : test_str = "geksefokesgergeeks", arg_str = "geeks" Output : 3 Explanation : "geeks" can be created 3 times using string characters. Input : test_str = "g
4 min read
Python | Get the string after occurrence of given substring
The problem involves getting the string that is occurring after the substring has been found. Let's discuss certain ways in which this task can be performed using Python.Using partition()To extract the portion of a string that occurs after a specific substring partition() method is an efficient and
3 min read
Python | Get the substring from given string using list slicing
Given a string, write a Python program to get the substring from given string using list slicing. Letâs try to get this using different examples. What is substring? A substring is a portion of a string. Python offers a variety of techniques for producing substrings, as well as for determining the in
4 min read
Python | Get matching substrings in string
The testing of a single substring in a string has been discussed many times. But sometimes, we have a list of potential substrings and check which ones occur in a target string as a substring. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension Using l
6 min read