Count Each Character

Count frequency of each character.

BeginnerPhase 5 - Category 1: Basic String HandlingExample 10 of 10
count-each-character.py
1# Take string input
2s = input("Enter a string: ")
3
4# Count characters
5freq = {}
6for char in s:
7 freq[char] = freq.get(char, 0) + 1
8
9# Display
10for char, count in sorted(freq.items()):
11 print(f"{char}: {count}")

Output

Enter a string: hello
e: 1
h: 1
l: 2
o: 1

What's going on

Use dictionary to count frequency.

Key Concepts:

Use dictionary to track counts
freq.get(char, 0) returns count or 0
Increment for each occurrence