Q:

Python | Find the frequency of each character in a string

belongs to collection: Python String Programs

0

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}

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Extract the mobile number from the given string in... >>
<< Python program to find the matched characters in a...