python

Frequency of each character in a Python String

If you want to get the frequency of each character in a Python string, you can use one of the methods listed in this post.

from collections import Counter

my_string = "congratulations"

result = Counter(my_string)
  
print(dict(result))
Output
{'c': 1, 'o': 2, 'n': 2, 'g': 1, 'r': 1, 'a': 2, 't': 2, 'u': 1, 'l': 1, 'i': 1, 's': 1}

The frequency of character in a string means how many times each character is repeated in the string. If you are using Python and want to get the frequency count of each character in a string, you can use the below methods.

Using Counter() function of collection module

The Counter() method from the Python collection module can be used to count the frequency of each character in a string.

Code Example

from collections import Counter

d_str = "devsheet"

result = Counter(d_str)
  
print(dict(result))

Output

{'d': 1, 'e': 3, 'v': 1, 's': 1, 'h': 1, 't': 1}

Count each character frequency using For Loop

To calculate the frequency of each character, we can also use Python for loop without using any functions(). This is a native method to get the each character count in a String.

Code Example

my_string = "devsheet"
char_frequencies = {}
  
for i in my_string:
    if i in char_frequencies:
        char_frequencies[i] += 1
    else:
        char_frequencies[i] = 1

print(char_frequencies)

Output

{'d': 1, 'e': 3, 'v': 1, 's': 1, 'h': 1, 't': 1}

Using get() function

We can also get the dictionary that contains the count of each character in a String using the get() function in Python.

Code Example

my_string = "helloworld"

result = {}

for keys in my_string:
  result[keys] = result.get(keys, 0) + 1

print(result)

Output

{'h': 1, 'e': 1, 'l': 3, 'o': 2, 'w': 1, 'r': 1, 'd': 1}
Was this helpful?