Python

How to Count Occurrences of Each Character in String – Python

In this tutorial, we are going to see how to count the number of occurrences of each character in a string and their positions in a string using collections.Counter().
 

How to Count Occurrences of Each Character using collections.Counter()

collections.Counter() accepts an iterable object as an argument and keeps its elements as keys and their frequency as values. So if we pass a string into collections.Counter(), it will return an object of class Counter that contains all the characters as keys and their frequency as values. So let’s use this to count the number of occurrences of each character in a string.
 

from collections import Counter

text = 'Lorem ipsum dolor sit pmet, consectetur adipiscing elit. '

frequency = Counter(text)
print("Count Occurrences of Each Character :")

for (key, value) in frequency.items():
    print("Number of occurrences of ", key, " is : ", value)

Output:

Count Occurrences of Each Character :
('Number of occurrences of ', 'a', ' is : ', 1)
('Number of occurrences of ', ' ', ' is : ', 7)
('Number of occurrences of ', 'c', ' is : ', 3)
('Number of occurrences of ', 'e', ' is : ', 5)
('Number of occurrences of ', 'd', ' is : ', 2)
('Number of occurrences of ', 'g', ' is : ', 1)
('Number of occurrences of ', 'i', ' is : ', 6)
('Number of occurrences of ', 'm', ' is : ', 3)
('Number of occurrences of ', 'L', ' is : ', 1)
('Number of occurrences of ', 'o', ' is : ', 4)
('Number of occurrences of ', 'l', ' is : ', 2)
('Number of occurrences of ', 'p', ' is : ', 3)
('Number of occurrences of ', 's', ' is : ', 4)
('Number of occurrences of ', 'r', ' is : ', 3)
('Number of occurrences of ', 'u', ' is : ', 2)
('Number of occurrences of ', 't', ' is : ', 5)
('Number of occurrences of ', '.', ' is : ', 1)
('Number of occurrences of ', 'n', ' is : ', 2)
('Number of occurrences of ', ',', ' is : ', 1)
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *