Write a python program to print the words in a sentence that are starting with a given letter and it must print how many words are there in that sentence with that letter. The program should input a sentence and a letter.
Answers
Answered by
3
Language:
Python
Program:
a=input(("Enter a sentence: ")).lower()
b=str(input("Enter a letter: ")).lower()
per=a.strip()
c=per.split(" ")
match=[]
inside=[]
#for words beginning with the letter
for i in c:
if i[0]==b:
match.append(i)
#for words that have the letter in them.
for j in c:
for k in j:
if k==b:
inside.append(j)
#prinitng the output values for match.
if len(match)==0:
print(f"\nThere are 0 words starting with {b}.")
else:
print(f"\nThere are {len(match)} words starting with {b} as followed:")
for i in match:
print(i)
#printing output values for inside.
print(f"\nThe words with {len(inside)} letter within.")
Output:
Consider the attachments.
Explanation:
- a takes sentence input and converts in into one of the cases ,i'm choosing lower one (to make search efficient) similarly b is taking the letter a input and converting it to lower case.
- a.strip() removes extra spaces before and after the sentence and saves it in per.
- per.split( " ") splits the line into pieces wherever there's space and saves it in a list.
- match and inside are initialized. Match stores words starting with the letter entered and Inside stores words that have that letter anywhere within we do that with the help of the followed two loops.
- Print the length and values stored with the help of another loop and else-if statements.
- print(f"{var}") will insert the value of var if defined in the program combines with the string.
Attachments:
Attachments:
Similar questions