Python Find the frequency of each character in a string

Recurrence of all characters in a string: Here, we will figure out how to discover the recurrence of each character in a string in Python?

Given a string and we need to discover the recurrence of each character of the string in Python.

Example:

    Input: 
    "hello"

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

Python code to discover recurrence 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}

Clarification:

In the above example fundamental () work executes first then it’ll request that the client enter the string as information. After that recurrence() will be called. user_input contains the string entered by the client.

user_input is currently gone through capacity. The capacity transforms every one of the characters into the lowercase after that utilizing for circle the frequencies of the considerable number of characters will be tallied.

And afterwards, an unfilled word reference will be made where characters will be put away as the estimations of the characters and frequencies will be put away as the keys of the lexicon.

Leave a Comment