w3resource

Python Program: Counting letters in a string


1. Counter of Letters

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

Sample Solution:

Code:

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}")

Output:

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:

Flowchart: Python Program: Counting letters in a string.

For more Practice: Solve these Related Problems:

  • Write a Python program to create a Counter of letters from a given string and print only those letters whose counts are even.
  • Write a Python script to generate a Counter from "Python Exercise!" and display the frequency of each character sorted alphabetically.
  • Write a Python function that strips punctuation from a string, then creates a Counter of letters and prints the three most common ones.
  • Write a Python program to create a Counter from "Python Exercise!" and then display the sum of all counts for alphabetic characters only.

Python Code Editor :

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.