Home » Python » Python programs

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?
Submitted by IncludeHelp, on August 09, 2019

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.