from collections import Counter
my_string = "congratulations"
result = Counter(my_string)
print(dict(result))
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.
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}
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}
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}
0 Comments