Python Program to Count the Frequency of Each Character in a String
Beginner · Strings
The frequency of a character is how many times it appears in a string; in "banana" the letter a has a frequency of 3. This program counts every character of a string with a dictionary, using the characters as keys and their counts as values.
Program
Character frequency in: programming in python p : 2 r : 2 o : 2 g : 2 a : 1 m : 2 i : 2 n : 3 y : 1 t : 1 h : 1
How it works
- The dictionary
frequencystarts empty, and each character becomes a key the first time it is seen. - If the character is already a key, its count goes up by one; otherwise it is added with a count of 1.
continueskips the spaces, so only letters and other visible characters are counted.- Dictionaries keep keys in the order they were added, so the output lists the characters in the order they first appear in the string.
- Capital and small letters are different characters here; use
text.lower()first to count them together.
Other ways to write it
Using collections.Counter
Counter({'n': 3, 'p': 2, 'r': 2, 'o': 2, 'g': 2, 'm': 2, 'i': 2, 'a': 1, 'y': 1, 't': 1, 'h': 1})
Top 3: [('n', 3), ('p', 2), ('r', 2)]Counter does all the counting in one step, and most_common(3) lists the three most frequent characters, with ties in the order they first appeared.
Using dict.get()
Character frequency in banana : {'b': 1, 'a': 3, 'n': 2}frequency.get(ch, 0) returns 0 for a character that has not been seen yet, which replaces the if/else with a single line.
Try it yourself
Change the program to count words instead of characters by looping over text.split().
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Count Vowels, Consonants, Uppercase and Lowercase Letters
- Count Vowels, Consonants, Uppercase and Lowercase Characters in a Text File
- Check a Palindrome String
- Reverse a String
- Generate a Random Password
- Count the Words in a String
- Remove Punctuation from a String
- Sort Words in Alphabetical Order
- Check if Two Strings Are Anagrams
All Python programs · CBSE class 12 practical file · Python exercises