Python Program to Find the Frequency of Characters in a String

In this python tutorial, you will learn how to Find the Frequency of Characters in a String with for loop and if else statements of the python programming language.

How to Find the Frequency of Characters in a String?

Let’s take a look at the source code,  here the values are assigned in the code, the for loop and if else statements carry out the function.

RUN CODE SNIPPET
#Python Program to Find the Frequency of Characters in a String

test_str = "DeveloperPublish"

all_freq = {}

for i in test_str:
    if i in all_freq:
        all_freq[i] += 1
    else:
        all_freq[i] = 1

print ("Count of all characters in DeveloperPublish is :\n "
                                        + str(all_freq))

OUTPUT:

Count of all characters in DeveloperPublish is :
{'D': 1, 'e': 3, 'v': 1, 'l': 2, 'o': 1, 'p': 1, 'r': 1, 'P': 1, 'u': 1, 'b': 1, 'i': 1, 's': 1, 'h': 1}
  1. At first, we declare the variable test_str with the input string value as "DeveloperPublish", after which we declare the variable all_freq and assign an empty curly brackets {}
  2. Then we open a for loop where the variable i is within the range test_str followed by a colon :
  3. We declare an if statement where the variable i is within the range all_freq, with the condition all_freq[i] += 1, after which we declare an else statement with the condition all_freq[i] = 1
  4. Finally, we declare a print function which will display the statement ("Count of all characters in DeveloperPublish is :\n " + str(all_freq)), in which the function + str(all_freq) will display the values with the integer and the string.

NOTE:

  • The print function is used to display the value, it prints the specified message to the screen
  •  The For loops are used to loop through an iterable object and perform the same action for each entry.
  • The if and else statements evaluates whether an expression is true or false. If a condition is true, the “if” statement is executed otherwise, the “else” statement is executed.
  •  The colon : at the end of the if and else statement tells Python that the next line of code should only be run if the condition is true.
  • The statement for the input function are enclosed in single quotes and parenthesis.
  • The \n in the code indicates a new line or the end of a statement line or a string.
  • The print statement/string to be displayed in enclosed in double quotes.

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...