Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Program to print strings based on the list of prefix
When it is required to print strings based on the list of prefix elements, a list comprehension, the any() operator and the startswith() method are used.
Example
Below is a demonstration of the same ?
my_list = ["streek", "greet", "meet", "leeks", "mean"]
print("The list is:")
print(my_list)
prefix_list = ["st", "ge", "me", "re"]
print("The prefix list is:")
print(prefix_list)
my_result = [element for element in my_list if any(element.startswith(ele) for ele in prefix_list)]
print("The result is:")
print(my_result)
Output
The list is: ['streek', 'greet', 'meet', 'leeks', 'mean'] The prefix list is: ['st', 'ge', 'me', 're'] The result is: ['streek', 'meet', 'mean']
How It Works
The solution uses a list comprehension with the any() function to check if each string starts with any of the given prefixes:
-
List comprehension − Iterates through each element in
my_list -
any() function − Returns
Trueif at least one condition is met - startswith() method − Checks if a string begins with a specific prefix
-
Generator expression −
(element.startswith(ele) for ele in prefix_list)creates boolean values for each prefix check
Alternative Method Using Loop
Here's an alternative approach using a traditional loop ?
my_list = ["streek", "greet", "meet", "leeks", "mean"]
prefix_list = ["st", "ge", "me", "re"]
result = []
for word in my_list:
for prefix in prefix_list:
if word.startswith(prefix):
result.append(word)
break # Found a match, no need to check other prefixes
print("The result is:")
print(result)
The result is: ['streek', 'meet', 'mean']
Conclusion
List comprehension with any() and startswith() provides a concise way to filter strings based on multiple prefixes. The alternative loop method offers more control but requires more code.
Advertisements
