Frequency of each character
EasyString Programs · 28 of 106
Write a Python program to count how often each character appears in a string.
Output{'s': 2, 'q': 1, 'a': 1, 't': 1, 'o': 2, 'l': 1}
True Approach
- 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 4get(ch, 0) handles the first time a character appears.
Learn the concept
New to this topic? Read the lesson, then come back.
More string programs
← All 106 String Programs