Count number of character available in String python

Find the Frequency of Characters in a String in Python

In this program, we will learn to find the occurrence of each character in the string. We will see a different example to count the number of characters or letters of the string.

Method – 1to find the no. of characters

In this method, we will use the count function to count each character. We will take dynamic input value or if you want then you can assign statically also.


#It will take user input

# if you want to assign any fixed particular value then you can do
#for that just assign the value to name eg: name='pramod'

name=input("enter your name:")

temp_name=""

for i in range(len(name)):

if name[i] not in temp_name:

print(f"{name[i]}:{name.count(name[i])}")

temp_name+=name[i]

i+=1

Output:

C:\Users\Pramod\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/Pramod/PycharmProjects/pythonProject/main.py
enter your name:Pramod Kumar Yadav
P:1
r:2
a:4
m:2
o:1
d:2
:2
K:1
u:1
Y:1
v:1

Process finished with exit code 0

Method- 2 To Count the Occurrence of each Character

In this method, we will use the naive method to count the character. In this method, Output will be in the form of a dictionary. Space will be also counted separately.

# Python3 code to demonstrate

# each occurrence frequency using

# naive method

# User input string

test_str = input('Enter you any Which you want to count: ')

# using naive method to get count

# of each element in string

#It will also ckount spaces

all_freq = {}


for i in test_str:

if i in all_freq:

all_freq[i] += 1

else:

all_freq[i] = 1

# printing result

print (f'Count of all characters "{test_str}" :\n '+ str(all_freq))
print(type(all_freq))

Output:

C:\Users\Pramod\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/Pramod/PycharmProjects/pythonProject/main.py
Enter you any Which you want to count: Pramod Kumar Yadav
Count of all characters "Pramod Kumar Yadav" :
{'P': 1, 'r': 2, 'a': 4, 'm': 2, 'o': 1, 'd': 2, ' ': 2, 'K': 1, 'u': 1, 'Y': 1, 'v': 1}
<class 'dict'>

Process finished with exit code 0

Recommended Post:

Get Salesforce Answers

Pramod Kumar Yadav is from Janakpur Dham, Nepal. He was born on December 23, 1994, and has one elder brother and two elder sisters. He completed his education at various schools and colleges in Nepal and completed a degree in Computer Science Engineering from MITS in Andhra Pradesh, India. Pramod has worked as the owner of RC Educational Foundation Pvt Ltd, a teacher, and an Educational Consultant, and is currently working as an Engineer and Digital Marketer.



Leave a Comment