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
test_list = [ "geeks" , "peeks" , "meeks" , "leeks" , "mean" ]
print ( "The original list is : " + str (test_list))
pref_list = [ "ge" , "ne" , "me" , "re" ]
res = [ele for ele in test_list if any (ele.startswith(el) for el in pref_list)]
print ( "The extracted prefix strings list : " + str (res))
|
Output
The 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
test_list = [ "geeks" , "peeks" , "meeks" , "leeks" , "mean" ]
print ( "The original list is : " + str (test_list))
pref_list = [ "ge" , "ne" , "me" , "re" ]
res = list ( filter ( lambda ele: any (ele.startswith(el)
for el in pref_list), test_list))
print ( "The extracted prefix strings list : " + str (res))
|
Output
The 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
test_list = [ "geeks" , "peeks" , "meeks" , "leeks" , "mean" ]
print ( "The original list is : " + str (test_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)
print ( "The extracted prefix strings list : " + str (res))
|
Output
The 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
test_list = [ "geeks" , "peeks" , "meeks" , "leeks" , "mean" ]
print ( "The original list is : " + str (test_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)
print ( "The extracted prefix strings list : " + str (res))
|
Output
The 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
test_list = [ "geeks" , "peeks" , "meeks" , "leeks" , "mean" ]
print ( "The original list is : " + str (test_list))
pref_list = [ "ge" , "ne" , "me" , "l" ]
pattern = '|' .join(pref_list)
res = []
for string in test_list:
matches = re.findall(pattern, string)
if any (matches):
res.append(string)
print ( "The extracted prefix strings list : " + str (res))
|
Output
The 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 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
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 th
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 print the dictionary in table format
Given a Dictionary. The task is to print the dictionary in table format. Examples: Input: {1: ["Samuel", 21, 'Data Structures'], 2: ["Richie", 20, 'Machine Learning'], 3: ["Lauren", 21, 'OOPS with java'], }Output: NAME AGE COURSE Samuel 21 Data Structures Richie 20 Machine Learning Lauren 21 OOPS wi
2 min read
Python program to count the number of characters in a String
The goal here is to count the number of characters in a string, which involves determining the total length of the string. For example, given a string like "GeeksForGeeks", we want to calculate how many characters it contains. Letâs explore different approaches to accomplish this. Using len()len() i
3 min read
Python program to check if lowercase letters exist in a string
Checking for the presence of lowercase letters involves scanning the string and verifying if at least one character is a lowercase letter (from 'a' to 'z'). Python provides simple and efficient ways to solve this problem using built-in string methods and constructs like loops and comprehensions. Usi
2 min read
Python program to calculate the number of digits and letters in a string
In this article, we will check various methods to calculate the number of digits and letters in a string. Using a for loop to remove empty strings from a list involves iterating through the list, checking if each string is not empty, and adding it to a new list. [GFGTABS] Python s = "Hello123!
3 min read
Python program to find the occurrence of substring in the string
Given a list of words, extract all the indices where those words occur in the string. Input : test_str = 'geeksforgeeks is best for geeks and cs', test_list = ["best", "geeks"] Output : [2, 4] Explanation : best and geeks occur at 2nd and 4th index respectively. Input : test_str = 'geeksforgeeks is
4 min read
Python Program To Find Longest Common Prefix Using Sorting
Problem Statement: Given a set of strings, find the longest common prefix.Examples: Input: {"geeksforgeeks", "geeks", "geek", "geezer"} Output: "gee" Input: {"apple", "ape", "april"} Output: "ap" The longest common prefix for an array of strings is the common prefix between 2 most dissimilar strings
2 min read