To print the words starting with a given letter in a user-entered string
Expt. No.13
Page No.26
Words starting with a letter
Aim
To write a Python program that prints the words in a user-entered string that start with a given letter.
Concepts used
Algorithm
- Input a sentence and a letter.
- Split the sentence into a list of words.
- For each word, if its first character (in lowercase) equals the letter, print the word.
Program
# Words in a string that start with a given letter sentence = input("Enter a sentence: ")letter = input("Enter a letter : ")words = sentence.split()print("Words starting with", letter, ":")for w in words: if w[0].lower() == letter.lower(): print(w)
A marked line continues the line above it. In your file, write it on the same line.
Output
$ python words_starting_with_letter.py
Enter a sentence: Students should save the program and see the output
Enter a letter : s
Words starting with s :
Students
should
save
see
✓ Printed by running this program, not typed by hand.
Result
Four words start with s: "Students", "should", "save" and "see". Comparing in lowercase also matched the capital S.
Viva voce: what the examiner may ask
01What does split() do?
It breaks the string at spaces and returns a list of words.
02What is w[0]?
The first character of the word.
03Why is lower() used on both sides?
So that "S" and "s" are treated as the same letter.
Variations for the lab test
- Count the words that start with a vowel.
- Print the words that end with the given letter.
- Print the words longer than 5 letters.
! Common mistake Comparing
w[0] == letter without lower() misses "Students" when the user types a small s.