Character Frequency Counter

Tags: Count, Loop, String

Write a Python program that counts the number of each character in a string. The string will be provided as a single line input.

Example 1:

Input: hello
h: 1
e: 1
l: 2
o: 1

Example 2:

Input: frequency
f: 1
r: 1
e: 2
q: 1
u: 1
n: 1
c: 1
y: 1

You can use a dictionary to store the count of each character. Then use a for loop to iterate through the string and update the count in the dictionary.

s = input()
freq = {}
for char in s:
    if char in freq:
        freq[char] += 1
        freq[char] = 1
for key, value in freq.items():
    print(key + ':', value)

© Let’s Data Science


Unlock AI & Data Science treasures. Log in!