Python: Find the strings in a list, starting with a given prefix
Python Programming Puzzles: Exercise-13 with Solution
Write a Python program to find strings in a given list starting with a given prefix.
Input: [( ca,('cat', 'car', 'fear', 'center'))] Output: ['cat', 'car'] Input: [(do,('cat', 'dog', 'shatter', 'donut', 'at', 'todo'))] Output: ['dog', 'donut']
Pictorial Presentation:

Sample Solution:
Python Code:
#License: https://bit.ly/3oLErEI
def test(strs, prefix):
return [s for s in strs if s.startswith(prefix)]
strs = ['cat', 'car', 'fear', 'center']
prefix = "ca"
print("Original strings:")
print(strs)
print("Starting prefix:", prefix)
print("Strings in the said list starting with a given prefix:")
print(test(strs, prefix))
strs = ['cat', 'dog', 'shatter', 'donut', 'at', 'todo']
prefix = "do"
print("\nOriginal strings:")
print(strs)
print("Starting prefix:", prefix)
print("Strings in the said list starting with a given prefix:")
print(test(strs, prefix))
Sample Output:
Original strings: ['cat', 'car', 'fear', 'center'] Starting prefix: ca Strings in the said list starting with a given prefix: ['cat', 'car'] Original strings: ['cat', 'dog', 'shatter', 'donut', 'at', 'todo'] Starting prefix: do Strings in the said list starting with a given prefix: ['dog', 'donut']
Flowchart:

Python Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Test whether the given strings are palindromes.
Next: Find the lengths of a list of non-empty strings.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join