Skip to content
Related Articles

Related Articles

Python program to find occurrence to each character in given string

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 20 May, 2019
View Discussion
Improve Article
Save Article

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.




# 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)) 

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




# 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)) 

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




# 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)) 

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
Recommended Articles
Page :

Start Your Coding Journey Now!