Python Practice › String Programs › Program 28

Frequency of each character

EasyString Programs · 28 of 106

Write a Python program to count how often each character appears in a string.

Advertisement
Input
"sqatools"
Output
{'s': 2, 'q': 1, 'a': 1, 't': 1, 'o': 2, 'l': 1}
True

Approach

  1. Build a dictionary of counts, or use Counter.

Solution

Python
text = "sqatools"freq = {}for ch in text:    freq[ch] = freq.get(ch, 0) + 1print(freq) from collections import Counterprint(Counter(text) == freq)
Output
{'s': 2, 'q': 1, 'a': 1, 't': 1, 'o': 2, 'l': 1}
True

Line by line

Line 4

get(ch, 0) handles the first time a character appears.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs