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:
- Python Hello World Program
- Python Comment | Creating a Comment | multiline comment | example
- Python Dictionary Introduction | Why to use dictionary | with example
- How to do Sum or Addition in python
- Python Reverse number
- find the common number in python
- addition of number using for loop and providing user input data in python
- Python Count char in String
- Python Last Character from String
- Python Odd and Even | if the condition
- Python Greater or equal number
- Python PALINDROME NUMBER
- Python FIBONACCI SERIES
- Python Dictionary | Items method | Definition and usage
- Python Dictionary | Add data, POP, pop item, update method
- Python Dictionary | update() method
- Delete statement, Looping in the list In Python
- Odd and Even using Append in python
- Python | Simple Odd and Even number
Get Salesforce Answers