Character Frequency in Python

Count the frequency of each character in a string.

BeginnerString ProgramsExample 10 of 25
character-frequency.py
Run in browser
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().