Python Program to print strings based on the list of prefix
Last Updated :
22 Apr, 2023
Given a Strings List, the task here is to write a python program that can extract all the strings whose prefixes match any one of the custom prefixes given in another list.
Input : test_list = ["geeks", "peeks", "meeks", "leeks", "mean"], pref_list = ["ge", "ne", "me", "re"]
Output : ['geeks', 'meeks', 'mean']
Explanation : geeks, meeks and mean have prefix, ge, me and me respectively, present in prefix list.
Input : test_list = ["geeks", "peeks", "meeks", "leeks", "mean"], pref_list = ["ge", "le", "me", "re"]
Output : ['geeks', 'meeks', 'mean', leeks]
Explanation : geeks, meeks, leeks and mean have prefix, ge, me, me and le respectively, present in prefix list.
Method 1: Using list comprehension, any() and startswith()
In this, we check all elements to match using any() and startswith() extracts all the prefixes. List comprehension is used to iterate through all the strings in the list.
Python3
# initializing List
test_list = ["geeks", "peeks", "meeks", "leeks", "mean"]
# printing original list
print("The original list is : " + str(test_list))
# initializing prefix list
pref_list = ["ge", "ne", "me", "re"]
# checking for all possible allowed prefixes using any()
res = [ele for ele in test_list if any(ele.startswith(el) for el in pref_list)]
# printing result
print("The extracted prefix strings list : " + str(res))
OutputThe original list is : ['geeks', 'peeks', 'meeks', 'leeks', 'mean']
The extracted prefix strings list : ['geeks', 'meeks', 'mean']
Time Complexity: O(n * m), where n is the number of elements in the test_list and m is the number of elements in the pref_list.
Auxiliary Space: O(n), where n is the number of elements in the result list 'res'.
Method 2 : Using filter(), lambda, any() and startswith()
This is similar to the above method, the difference being that filtering is performed using filter() and lambda.
Python3
# initializing List
test_list = ["geeks", "peeks", "meeks", "leeks", "mean"]
# printing original list
print("The original list is : " + str(test_list))
# initializing prefix list
pref_list = ["ge", "ne", "me", "re"]
# checking for all possible allowed prefixes using any()
# filtering using filter() and lambda
res = list(filter(lambda ele: any(ele.startswith(el)
for el in pref_list), test_list))
# printing result
print("The extracted prefix strings list : " + str(res))
OutputThe original list is : ['geeks', 'peeks', 'meeks', 'leeks', 'mean']
The extracted prefix strings list : ['geeks', 'meeks', 'mean']
Time Complexity : O(n2)
Auxiliary Space : O(n)
Method 3 : Using find() method
Python3
# initializing List
test_list = ["geeks", "peeks", "meeks", "leeks", "mean"]
# printing original list
print("The original list is : " + str(test_list))
# initializing prefix list
pref_list = ["ge", "ne", "me", "re"]
res = []
for i in test_list:
for j in pref_list:
if(i.find(j) == 0):
res.append(i)
# printing result
print("The extracted prefix strings list : " + str(res))
OutputThe original list is : ['geeks', 'peeks', 'meeks', 'leeks', 'mean']
The extracted prefix strings list : ['geeks', 'meeks', 'mean']
Time complexity: O(n^2), where n is the length of the test_list.
Auxiliary space: O(m), where m is the length of the res list (the space required to store the extracted prefix strings).
Method 4 : Using for loop, len() method and slicing
Python3
# Python Program to print strings based on
# the list of prefix initializing List
test_list = ["geeks", "peeks", "meeks", "leeks", "mean"]
# Printing original list
print("The original list is : " + str(test_list))
# Initializing prefix list
pref_list = ["ge", "ne", "me", "l"]
res = []
for i in test_list:
for j in pref_list:
if(i[:len(j)]==j):
res.append(i)
# Printing result
print("The extracted prefix strings list : " + str(res))
OutputThe original list is : ['geeks', 'peeks', 'meeks', 'leeks', 'mean']
The extracted prefix strings list : ['geeks', 'meeks', 'leeks', 'mean']
Time complexity: O(n*m), where n is the length of test_list and m is the length of pref_list.
Auxiliary space: O(k), where k is the length of res.
Method 7: Using regex
Step-by-step approach:
Import the re module to use regular expressions.
Define a regular expression pattern that matches any of the prefixes in pref_list, using the | (or) operator to separate them.
Use the re.findall() function to find all matches of the pattern in each string in test_list.
Use the any() function to check if there is at least one match for each string in test_list.
If a string has at least one match, add it to the result list, res.
Print the res list.
Python3
import re
# Python Program to print strings based on
# the list of prefix initializing List
test_list = ["geeks", "peeks", "meeks", "leeks", "mean"]
# Printing original list
print("The original list is : " + str(test_list))
# Initializing prefix list
pref_list = ["ge", "ne", "me", "l"]
# Defining regex pattern
pattern = '|'.join(pref_list)
# Initializing result list
res = []
# Iterating through each string in test_list
for string in test_list:
# Finding all matches of pattern in string
matches = re.findall(pattern, string)
# Checking if there is at least one match
if any(matches):
res.append(string)
# Printing result
print("The extracted prefix strings list : " + str(res))
OutputThe original list is : ['geeks', 'peeks', 'meeks', 'leeks', 'mean']
The extracted prefix strings list : ['geeks', 'meeks', 'leeks', 'mean']
Time complexity: O(n*m), where n is the length of test_list and m is the length of pref_list.
Auxiliary space: O(n), where n is the length of test_list. This is because we store the result in a list that may contain up to n items.
Similar Reads
Python program to find String in a List
Searching for a string in a list is a common operation in Python. Whether we're dealing with small lists or large datasets, knowing how to efficiently search for strings can save both time and effort. In this article, weâll explore several methods to find a string in a list, starting from the most e
3 min read
Python Program to Convert a List to String
In Python, converting a list to a string is a common operation. In this article, we will explore the several methods to convert a list into a string. The most common method to convert a list of strings into a single string is by using join() method. Let's take an example about how to do it.Using the
3 min read
Python program to find the character position of Kth word from a list of strings
Given a list of strings. The task is to find the index of the character position for the word, which lies at the Kth index in the list of strings. Examples: Input : test_list = ["geekforgeeks", "is", "best", "for", "geeks"], K = 21 Output : 0Explanation : 21st index occurs in "geeks" and point to "g
3 min read
Print Substrings that are Prefix of the Given String - Python
The task of printing the substrings that are prefixes of a given string involves generating all the possible substrings that start from the first character of the string and end at any subsequent position.For example, if the given string is s = "hello", the prefixes of the string would include "h",
3 min read
Python program to find Indices of Overlapping Substrings
To count the number of overlapping sub-strings in Python we can use the Re module. To get the indices we will use the re.finditer() method. But it returns the count of non-overlapping indices only. Examples: Input: String: "geeksforgeeksforgeeks" ; Pattern: "geeksforgeeks" Output: [0, 8] Explanation
4 min read
Python program to split a string by the given list of strings
Given a list of strings. The task is to split the string by the given list of strings. Input : test_str = 'geekforgeeksbestforgeeks', sub_list = ["best"] Output : ['geekforgeeks', 'best', 'forgeeks'] Explanation : "best" is extracted as different list element. Input : test_str = 'geekforgeeksbestfor
4 min read
Python | Append suffix/prefix to strings in list
Sometimes, while working with Python, we can a problem in which we need to pad strings in lists at trailing or leading position. This kind of problem is quite common and can occur in day-day programming or web development. Let's discuss a way in which this task can be performed. Method #1: Using + o
5 min read
Python program to print k characters then skip k characters in a string
Given a String, extract K characters alternatively. Input : test_str = 'geeksgeeksisbestforgeeks', K = 4 Output : geekksisforg Explanation : Every 4th alternate range is sliced. Input : test_str = 'geeksgeeksisbest', K = 4 Output : geekksis Explanation : Every 4th alternate range is sliced. Method #
5 min read
Python Program to Check Overlapping Prefix - Suffix in Two Lists
Given 2 Strings, our task is to check overlapping of one string's suffix with prefix of other string. Input : test_str1 = "Gfgisbest", test_str2 = "bestforall" Output : best Explanation : best overlaps as suffix of first string and prefix of next. Input : test_str1 = "Gfgisbest", test_str2 = "restfo
4 min read
Python Program to print strings with repetitive occurrence of an element in a list
Given a strings List, write a Python program that extracts all the strings with more than one occurrence of a specific value(here described using K) in elements of a list. Examples: Input : test_list = ["geeksforgeeks", "best", "for", "geeks"], K = 'e' Output : ['geeksforgeeks', 'geeks'] Explanation
5 min read