In this article, we will explore various methods to extract words starting with K in String List. The simplest way to do is by using a loop.
Using a Loop
We use a loop (for loop) to iterate through each word in the list and check if it starts with the exact character (case-sensitive) provided in the variable.
a = ["Kite", "Apple", "King", "Banana", "Kangaroo", "cat"]
# Character to match (case-sensitive)
K = 'K'
# List to store words starting with given character
res = []
# Loop through the list and check
# if the word starts with character K
for word in a:
if word.startswith(K):
res.append(word)
print(f"Words starting with '{K}':", res)
Output
Words starting with 'K': ['Kite', 'King', 'Kangaroo']
Explanation:
- word.startswith(K): Checks if word starts with the character stored in K without any case modification.
- Only the words that exactly match the case of K will be included in the result.
Let's explore other different methods:
Table of Content
Using List Comprehension
List comprehension is a more concise and Pythonic approach to extract words starting with the specified character (case-sensitive).
a = ["Kite", "Apple", "King", "Banana", "Kangaroo", "cat"]
# Character to match (case-sensitive)
K = 'K'
# Using list comprehension to extract words
# starting with the character K
res = [word for word in a if word.startswith(K)]
print(f"Words starting with '{K}':", res)
Output
Words starting with 'K': ['Kite', 'King', 'Kangaroo']
Using filter() Function
filter() function provides a functional programming approach to filter out words starting with the given character (case-sensitive).
a = ["Kite", "Apple", "King", "Banana", "Kangaroo", "cat"]
# Character to match (case-sensitive)
K = 'K'
# Using filter() and lambda function to extract
# words starting with the character K
res = list(filter(lambda word: word.startswith(K), a))
print(f"Words starting with '{K}':", res)
Output
Words starting with 'K': ['Kite', 'King', 'Kangaroo']
Explanation:
- filter() applies the lambda function to each word in the list a.
- lambda word: word.startswith(K) checks if the word starts with the exact character stored in K.