Character Frequency

Count the frequency of each character in a string.

PythonBeginner
Python
# Program to count frequency of each character in a string

s = input("Enter a string: ")

freq = {}
for ch in s:
    freq[ch] = freq.get(ch, 0) + 1

for ch, count in freq.items():
    print(f"{ch!r}: {count}")

Output

Enter a string: aba
'a': 2
'b': 1

We build a dictionary mapping each character to the number of times it appears using dict.get().