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 Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read