Find the occurrence of each character in string using python

Method 1: Count function :

The count function is used to count the occurrence of each character in string. Here we can give the specific character in count function and it will return the number of occurrence in that string.

Example :

>> sample_string = “hello world”
>>> sample_string.count(‘h’)

Output: 1

Method 2 : Get the all character occurrence in string using dictionary

Here the dictionary variable (example : all_freq ={}) used to store the each character occurrence of the input string.The for loop is iterate each character in the input string and count the frequency of character and store the results in the dictionary variable.


Output :

Count of occurrence :
{‘x’: 4, ‘y’: 2, ‘a’: 3, ‘b’: 1, ‘c’: 1}

Python program to print the required character based on character occurrence

We can validate the each character occurrence in string and print the required character alone by validate the counter value.