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}
- At first, we declare the variable
test_str
with the input string value as"DeveloperPublish"
, after which we declare the variableall_freq
and assign an empty curly brackets{}
- Then we open a
for
loop where the variablei
is within the rangetest_str
followed by a colon:
- We declare an
if
statement where the variablei
is within the rangeall_freq
, with the conditionall_freq[i] += 1
, after which we declare anelse
statement with the conditionall_freq[i] = 1
- 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.