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']

Explanation

  • A list of strings is defined and is displayed on the console.
  • A list of strings is defined as ‘prefix_list’ and is displayed on the console.
  • A list comprehension is used to iterate over the elements and check if an element in the list starts with any of the strings provided in the prefix list.
  • If yes, the element is stored in a list.
  • This is assigned to a variable.
  • This is displayed as output on the console.

Updated on: 16-Sep-2021

309 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements