Python Program to count occurrence of characters in string

Ans: 

In this tutorial we will learn how to write program in Python to count occurrence of character in a String.

 

Also Read this:  C program to count the occurrence of a character in String.

How this Python program will behave?

This Python program will take a string and a character as an input. And it will count the  occurrence of a given character. This program will also count spaces I we will give it.

For example:
If we have given a String as an input “Quescol is educational website” and also a character ‘s’.

Then after counting character ‘a’, program will return output 2.

Python Program to count the occurrence of given character in a string.

Using for Loop:

string = input("Please enter String : ")
char = input("Please enter a Character : ")
count = 0
for i in range(len(string)):
    if(string[i] == char):
        count = count + 1
print("Total Number of occurence of ", char, "is :" , count)
 

Output:

count characters in string

Using while Loop:

string = input("Please enter String : ")
char = input("Please enter a Character : ")
index, count = 0, 0
while(index < len(string)):
    if(string[index] == char):
        count = count + 1
    index = index + 1
print("Total Number of occurence of ", char, "is :" , count)
 

Output:

count characters in string

Using Method:

def countOccur(char, string):
    count = 0
    for i in range(len(string)):
        if(string[i] == char):
            count = count + 1
    return count
string = input("Please enter String : ")
char = input("Please enter a Character : ")
count = countOccur(char, string)
print("Total Number of occurence of ", char, "is :" , count) 

Output:

count characters in string