Count the number of occurrence of given alphabet in a string in python

Here, we are going to write python program to count the number of occurrence of given alphabet in a string in python. We can use regular expression to find the number of occurrences of any alphabet in given string. We can use count() function ,counter() collections or for loop too to count the number of occurrences of given alphabet in string . In this program, we will use regular expression to find it. To use regular expression method or function in program, we need to import re module. import statement allow us to use all the contents like function,method of module. so first we will import re module and then use findall method .findall method will find all the occurrences of given alphabet in string and count it.

Python program using regular expression

import re
s = input("Enter any sentence :")  
print("Original string:")
print(s)
print("Number of occurrence of given alphabet in the said string:")
o = input("Enter any alphabet :")
ctr = len(re.findall(o, s))
print("Total number of given alphabet :",ctr)


Output:

Enter any sentence :athang bhnauprakash dixit
Original string:
athang bhnauprakash dixit
Number of occurrence of given alphabet in the said string:
Enter any alphabet :a
Total number of given alphabet : 5

Watch other python programs

<