Character Frequency in Python

Count the frequency of each character in a string.

BeginnerString ProgramsExample 10 of 25
character-frequency.py
1# Program to count frequency of each character in a string
2
3s = input("Enter a string: ")
4
5freq = {}
6for ch in s:
7 freq[ch] = freq.get(ch, 0) + 1
8
9for ch, count in freq.items():
10 print(f"{ch!r}: {count}")

Output

Enter a string: aba
'a': 2
'b': 1

What's going on

We build a dictionary mapping each character to the number of times it appears using dict.get().

After this program

If the idea is still fuzzy, read Day 4: Strings and String Methods in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 string programs, or see every topic on Python exercises.