196k views
7 votes
4.16 LAB: Count characters Write a program whose input is a character and a string, and whose output indicates the number of times the character appears in the string. The output should include the input character and use the plural form, n's, if the number of times the characters appears is not exactly 1. Ex: If the input is: n Monday the output is: 1 n Ex: If the input is: z Today is Monday the output is: 0 z's Ex: If the input is: n It's a sunny day the output is: 2 n's Case matters. Ex: If the input is: n Nobody the output is: 0 n's

1 Answer

4 votes

Answer:

In Python:

sttr = input("String: ")

ch = input("Character: ")

count = sttr.count(ch)

print(str(count)+" "+ch, end = '')

if count>1 or count==0:

print("'s")

Step-by-step explanation:

This prompts the user for string

sttr = input("String: ")

This prompts the user for character

ch = input("Character: ")

This counts the number of occurrence

count = sttr.count(ch)

This prints the number of occurrence of the character

print(str(count)+" "+ch, end = '')

This checks if the number of occurrence is 0 or greater than 1.

if count>1 or count==0:

If yes, it prints 's

print("'s")

User Rafael Beirigo
by
8.5k points