In this post, we will learn how to calculate frequency of a characters in Python using for-loop, while-loop, python dictionary, and dictionary comprehension with detailed explanations and examples.
So let’s start writing a program to calculate the frequency of a characters in Python using all the different ways one by one.
Calculate Frequency of a Characters in Python using for-loop
Few programming concepts you have to know before writing this program:
Source Code:
my_str = input("Enter your String: ")
tem = ""
# This temporary (tem) variable helps you to count each character only once
for char in my_str:
if char not in tem:
tem+=char
print(f"{char} : {my_str.count(char)}")
Output:
Enter your String: allinpython
a : 1
l : 2
i : 1
n : 2
p : 1
y : 1
t : 1
h : 1
o : 1
Calculate Frequency of a Characters in Python using while-loop
Few programming concepts you have to know before writing this program:
Source Code:
my_str = input("Enter your String: ")
tem = ""
# This temporary (tem) variable helps you to count each character only once
i = 0
while i < len(my_str):
if my_str[i] not in tem:
tem+= my_str[i]
print(f"{my_str[i]} : {my_str.count(my_str[i])}")
i+=1
Output:
Enter your String: learn with allinpython
l : 3
e : 1
a : 2
r : 1
n : 3
: 2
w : 1
i : 2
t : 2
h : 2
p : 1
y : 1
o : 1
Calculate Frequency of a Characters in Python using Dictionary
Few programming concepts you have to know before writing this program:
Source Code:
my_str = input("Enter your String: ")
char_count = {}
for char in my_str:
char_count.update({char: my_str.count(char)})
print(char_count)
Output:
Enter your String: yagyavendra
{'y': 2, 'a': 3, 'g': 1, 'v': 1, 'e': 1, 'n': 1, 'd': 1, 'r': 1}
Note: As the Python dictionary takes the unique keys (there are no duplicate keys present in the dictionary) that’s why each character counts only once.
Calculate Frequency of a Characters in Python using Dictionary Comprehension
Few programming concepts you have to know before writing this program:
Source Code:
string = input("Enter your String: ")
char_counter = {char: string.count(char) for char in string}
print(char_counter)
Output:
Enter your String: aaaalllinnnaaa
{'a': 7, 'l': 3, 'i': 1, 'n': 3}