Python Program to Find Frequency of Characters in a String

In Python, a string is a sequence of characters that you can use to store data. You can also create a string using the str() function, which takes an argument of type string.

This function returns a string that contains the data that was passed in as an argument.

Program Code

#take the input from user
input_string = input("Enter the string: ")

#find the frequency of each character in the input string
frequency_of_each_character = {}
for character in input_string:
    if character in frequency_of_each_character:
        frequency_of_each_character[character] += 1
        frequency_of_each_character[character] = 1

#print the frequency of each character along with character
for character, frequency in frequency_of_each_character.items():
    print("{} : {}".format(character, frequency))

Input Given:

Enter the string: edupepper

Expected Output:

e : 3
d : 1
u : 1
p : 3
r : 1

Code Explanation

  1. Take the input from the user
  2. Create a dictionary to store the frequency of each character
  3. Iterate over the input string and check if the character is already present in the dictionary. If yes, increment the frequency by 1. If not, add the character to the dictionary with frequency 1.
  4. Iterate over the dictionary and print the character and its frequency.

Leave a Comment

Share to...