Print frequency of each character in a string in Python

In this tutorial, we will learn how to print the frequency of each character in a string using Python.

Frequency of each character in a string

For that, we have two methods.

  1. Using basic logic.
  2. Counter() method.

Let’s start with the first one.

if-else statement (Basic logic)

First of all, let’s take a string for which we have to find the frequency of each character.

my_string = "Nitesh Jhawar"

We will define an empty dictionary, freq_dict. This dictionary will contain each character and its frequency in the key-value pairs. For example,
freq_dict={‘N’: 1,’i’:1}.
The key represents the character and the frequency represents its respective frequency.

freq_dict = {}

Now, its time to use for loop.

for i in my_string: 
    if i in freq_dict: 
        freq_dict[i]=freq_dict[i] + 1
    else: 
        freq_dict[i] = 1

Here, we have used a for loop to iterate through the characters in my_string using the iterating variable i.

After that, we use the if-else statement. If exists in our dictionary, then we increase the frequency count by 1 otherwise we will initialize the value to 1.

Finally, We need to print our dictionary.

print ("Characters with their frequencies:\n",freq_dict)

And the output will be,

Characters with their frequencies:
{'N': 1, 'i': 1, 't': 1, 'e': 1, 's': 1, 'h': 2, ' ': 1, 'J': 1, 'a': 2, 'w': 1, 'r': 1}

Counter() method

In Python, we have a module named collections. It is a container that is used to store data such as a dictionary, list, etc. collections module contains a method Counter() which is also a container that stores data in the form of a dictionary i.e, elements as key and its frequency as value.
Syntax:
Counter(string_name)

Now, let’s use it.

from collections import Counter 

my_string = "Nitesh Jhawar"
freq_dict = Counter(my_string)  

print ("Characters with their frequencies:\n",freq_dict)

From the collections module, we have an imported Counter method.

The dictionary returned by Counter() is stored in freq_dict. It is then printed using the print statement.

Output:

Characters with their frequencies:
Counter({'h': 2, 'a': 2, 'N': 1, 'i': 1, 't': 1, 'e': 1, 's': 1, ' ': 1, 'J': 1, 'w': 1, 'r': 1})

Also, learn:

 

 

Leave a Reply

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