Python | Find the frequency of each character in a string

Frequency of all characters in a string: Here, we are going to learn how to find the frequency of each character in a string in Python? By IncludeHelp Last updated : February 25, 2024

Problem statement

Given a string and we have to find the frequency of each character of the string in Python.

Example

Input: 
"hello"

Output:
{'o': 1, 'h': 1, 'e': 1, 'l': 2}

Python code to find frequency of the characters

# Python program to find the frequency of 
# each character in a string

# function definition
# it accepts a string and returns a dictionary 
# which contains the frequency of each chacater
def frequency(text):
    # converting string to lowercase
    text = text.lower()
    # dictionary declaration
    dict = {}
    # traversing the characters
    for char in text:
        keys = dict.keys()
        if char in keys:
            dict[char] += 1
        else:
            dict[char] = 1
    return dict

# main code
if __name__ == '__main__':
    # inputting the string and printing the frequency
    # of all characters
    user_input = str(input("Enter a string: "))
    print(frequency(user_input))

    user_input = str(input("Enter another string: "))
    print(frequency(user_input))

Output

Enter a string: Hello
{'o': 1, 'h': 1, 'e': 1, 'l': 2}
Enter another string: aabbcc bb ee dd
{'a': 2, 'd': 2, 'e': 2, 'b': 4, 'c': 2, ' ': 3}

Explanation

In the above example main () function execute first then it'll ask the user to enter the string as input. After that frequency() will be called. user_input contains the string entered by the user. user_input is now passed through the function. The function turns all the characters into the lowercase after that using for loop the frequencies of all the characters will be counted. And then, an empty dictionary will be created where characters will be stored as the values of the characters and frequencies will be stored as the keys of the dictionary.

To understand the above program, you should have the basic knowledge of the following Python topics:

Python String Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.