Editor

Python Program to Count the Frequency of Each Character in a String

Beginner · Strings

The frequency of a character is how many times it appears in a string; in "banana" the letter a has a frequency of 3. This program counts every character of a string with a dictionary, using the characters as keys and their counts as values.

Program

character_frequency.py
text = "programming in python" # or: text = input("Enter a string: ")
frequency = {}
for ch in text:
if ch == " ":
continue # skip spaces
if ch in frequency:
frequency[ch] += 1
else:
frequency[ch] = 1
print("Character frequency in:", text)
for ch, count in frequency.items():
print(ch, ":", count)
Output
Character frequency in: programming in python
p : 2
r : 2
o : 2
g : 2
a : 1
m : 2
i : 2
n : 3
y : 1
t : 1
h : 1

How it works

  1. The dictionary frequency starts empty, and each character becomes a key the first time it is seen.
  2. If the character is already a key, its count goes up by one; otherwise it is added with a count of 1.
  3. continue skips the spaces, so only letters and other visible characters are counted.
  4. Dictionaries keep keys in the order they were added, so the output lists the characters in the order they first appear in the string.
  5. Capital and small letters are different characters here; use text.lower() first to count them together.

Other ways to write it

Using collections.Counter

Using collections.Counter
from collections import Counter
text = "programming in python"
frequency = Counter(text.replace(" ", ""))
print(frequency)
print("Top 3:", frequency.most_common(3))
Output
Counter({'n': 3, 'p': 2, 'r': 2, 'o': 2, 'g': 2, 'm': 2, 'i': 2, 'a': 1, 'y': 1, 't': 1, 'h': 1})
Top 3: [('n', 3), ('p', 2), ('r', 2)]

Counter does all the counting in one step, and most_common(3) lists the three most frequent characters, with ties in the order they first appeared.

Using dict.get()

Using dict.get()
text = "banana"
frequency = {}
for ch in text:
frequency[ch] = frequency.get(ch, 0) + 1
print("Character frequency in", text, ":", frequency)
Output
Character frequency in banana : {'b': 1, 'a': 3, 'n': 2}

frequency.get(ch, 0) returns 0 for a character that has not been seen yet, which replaces the if/else with a single line.

Try it yourself

Change the program to count words instead of characters by looping over text.split().

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises