Python program to find occurrence to each character in given string

Given a string, the task is to write a program in Python which prints the number of occurrences of each character in a string.

There are multiple ways in Python, we can do this task. Let’s discuss a few of them.

Method #1: Using set() + count()

Iterate over the set converted string and get the count of each character in original string.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to program to find occurrence
# to each character in given string
  
# initializing string 
inp_str = "GeeksforGeeks"
  
# using set() + count() to get count 
# of each element in string 
out = {x : inp_str.count(x) for x in set(inp_str )} 
  
# printing result 
print ("Occurrence of all characters in GeeksforGeeks is :\n "+ str(out)) 

chevron_right


Output:

Occurrence of all characters in GeeksforGeeks is :
 {'o': 1, 'r': 1, 'e': 4, 's': 2, 'f': 1, 'G': 2, 'k': 2}

 
Method #2: Using dictionary

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to program to find occurrence
# to each character in given string
  
# initializing string 
inp_str = "GeeksforGeeks"
  
# frequency dictionary
freq = {} 
    
for ele in inp_str: 
    if ele in freq: 
        freq[ele] += 1
    else
        freq[ele] = 1
    
# printing result  
print ("Occurrence of all characters in GeeksforGeeks is :\n "+ str(freq)) 

chevron_right


Output:

Occurrence of all characters in GeeksforGeeks is :
 {'e': 4, 'r': 1, 'o': 1, 'f': 1, 'G': 2, 's': 2, 'k': 2}

 
Method #3: Using collections

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to program to find occurrence
# to each character in given string
from collections import Counter 
    
# initializing string  
in_str = "GeeksforGeeks"
    
# using collections.Counter() to get  
# count of each element in string  
oup = Counter(in_str) 
    
# printing result  
print ("Occurrence of all characters in GeeksforGeeks is :\n "+ str(oup)) 

chevron_right


Output:

Occurrence of all characters in GeeksforGeeks is :
 Counter({'e': 4, 's': 2, 'G': 2, 'k': 2, 'f': 1, 'r': 1, 'o': 1})


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.