Python Program: Counting letters in a string

Python Counter Data Type: Exercise-1 with Solution

Write a Python program to create a 'Counter' of the letters in the string "Python Exercise!".

Sample Solution:


from collections import Counter

text = "Python Exercise!"
letter_counter = Counter(text)

print("Letter Counter:")
for letter, count in letter_counter.items():
    if letter.isalpha():
        print(f"{letter}: {count}")


Letter Counter:
P: 1
y: 1
t: 1
h: 1
o: 1
n: 1
E: 1
x: 1
e: 2
r: 1
c: 1
i: 1
s: 1

In the exercise above "Counter" class from the "collections" module to count the occurrences of each letter in the given string. It then iterates through the items in the "Counter" and prints the counts of letters that are alphabetic characters.


Flowchart: Python Program: Counting letters in a string.

Previous: Python Extended Data Type Counter Exercises Home.
Next: Python Program: Counting common elements in a list.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

Summing a sequence of numbers (calculating the sum of zero to ten with skips):

>>> l = range(0,10,2)
>>> sum(l)


We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook