Exercise 26
Write a Python algorithm that asks the user to enter a string text and return all words beginning with the letter 'a'.
Solution
First method:
# Ask the user to enter a string text s = input("Type a string text : ") # convert a string s to list s = s.split() # fetching all list element that beginning with the letter 'a' for x in s: if(x[0] == 'a'): print("The word : ", x, " begin with the letter 'a'") """ output: Type a string text : Me and you are beginner The word : 'and' begin with the letter 'a' The word : 'are' begin with the letter 'a' """
Explanation:
- The input("..."): is used to prompt the user to enter a string text
- s.split(): convert the string s to list of word
- for loop: is used to iterate over all word of the string s.
- if(x[0] == 'a'): then we test if the word 'x' begin withe the letter 'a'
- The print() function: is used to print and display the result.
Second method:
text = input("Enter some text: ") # Ask the user to enter a text # Split the text into words and filter out words that don't start with "a" words = [word for word in text.split() if word.startswith("a")] # Print the filtered words print("Words starting with 'a':") for word in words: print(word)
Younes Derfoufi
my-courses.net
[…] Exercise 26 * || Solution […]