Character Frequency
Count the frequency of each character in a string.
BeginnerTopic: String Programs
Python Character Frequency Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# 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
Understanding Character Frequency
We build a dictionary mapping each character to the number of times it appears using dict.get().
Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.