Exercise 17

Write a program in Python to display for a given string the number of occurrences of each character in the string.
Example for the string s = "Python Programming" the program must display:
The character ' P ' appears 2 time(s) in the string s
The character ' y ' appears 1 time(s) in the string s
The character ' t ' appears 1 time(s) in the string s
The character ' h ' appears 1 time(s) in the string s
The character ' o ' appears 2 time(s) in the string s
The character ' n ' appears 2 time(s) in the string s
The character ' ' appears 1 time(s) in the string s
The character ' r ' appears 2 time(s) in the string s
The character ' g ' appears 2 time(s) in the string s
The character ' a ' appears 1 time(s) in the string s
The character ' m ' appears 2 time(s) in the string s
The character ' i ' appears 1 time(s) in the string s

Solution

s = "Python programming"

# Create a unique list to avoid redundancy
unique = []

# iterate over all charchters of the string s
for x in s:
    if x not in unique:
        unique.append(x)
        print("TThe character ", x, " appears " , s.count(x), " time(s) in the string s")




 

Younes Derfoufi
CRMEF OUJDA

One thought on “Solution Exercise 17: display the number of occurrences of each character in given string”

Leave a Reply