Python Practice › List Programs › Program 52
Items starting with a letter
Write a Python program to find the items that start with a given character.
Input
["abbcd", "ppq", "abdd", "agr", "bhr", "sqqa", "tools", "bgr"]; letters a, b, c
Output
a ['abbcd', 'abdd', 'agr'] b ['bhr', 'bgr'] c []
Approach
- Filter with
startswith().
Solution
items = ["abbcd", "ppq", "abdd", "agr", "bhr", "sqqa", "tools", "bgr"]for letter in "abc": print(letter, [w for w in items if w.startswith(letter)])Output
a ['abbcd', 'abdd', 'agr'] b ['bhr', 'bgr'] c []
Learn the concept
New to this topic? Read the lesson, then come back.