Character Frequency in Python
Count the frequency of each character in a string.
BeginnerString ProgramsExample 10 of 25
character-frequency.py
Run in browser1# Program to count frequency of each character in a string23s = input("Enter a string: ")45freq = {}6for ch in s:7 freq[ch] = freq.get(ch, 0) + 189for 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().