Determine the frequency of each character in a string.

Last updated 4 months, 1 week ago | 224 views 75     5

Tags:- Python

You can determine the frequency of each character in a string using Python's collections.Counter or a simple dictionary.

Method 1: Using collections.Counter (Efficient)

from collections import Counter

text = "hello world"
print(dict(Counter(text)))


#Output: {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}

Method 2: Manual Counting

def char_frequency(s):
    freq = {}
    for char in s:
        freq[char] = freq.get(char, 0) + 1
    return freq

print(char_frequency("hello world"))


# Output: {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}

This approach manually counts character occurrences using a dictionary.

Both methods will give you the frequency of each character, including spaces.