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.
# 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)) |
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 dictionaryfreq = {} 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)) |
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 stringfrom 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)) |
Occurrence of all characters in GeeksforGeeks is :
Counter({'e': 4, 's': 2, 'G': 2, 'k': 2, 'f': 1, 'r': 1, 'o': 1})
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


