Home / Python / Example programs / Strings

Python program: Count each character

Count how many times each character appears in a word.

The code

word = "mississippi"
counts = {}
for ch in word:
    counts[ch] = counts.get(ch, 0) + 1
print(counts)

for ch, n in sorted(counts.items(), key=lambda kv: -kv[1]):
    print(ch, "#" * n)

Output

{'m': 1, 'i': 4, 's': 4, 'p': 2}
i ####
s ####
p ##
m #

How it works

The counting pattern with dict.get, then a sorted bar chart made of # characters.

Python features used

Learn the ideas behind it in the free lesson Dictionaries & Sets.