;

Python Program to Count Occurrence of a Specific Character in a String


Tutorialsrack 27/04/2020 Python

In this Python program, we will learn how to count occurrences of a specific character in a string. We used the for and while loop to count occurrences of a specific character in a string. 

Here is the source code of the program to count occurrences of a specific character in a string.

Program 1: Python Program to Count Occurrence of a Specific Character in a String Using For Loop

Python Program to Count Occurrence of a Specific Character in a String Using For Loop
# Python Program to Count Occurrence of a Specific Character in a String Using For Loop

# Take the Input rom the User
string = input("Enter the String: ")
char = input("Enter the Character: ")

count = 0
for i in range(len(string)):
    if(string[i] == char):
        count = count + 1

print("The total Number of Times ", char, " has Occurred = " , count)
Output

Enter the String: Tutorials Rack is an Online Learning Website

Enter the Character: i

The total Number of Times  i  has Occurred =  5

Program 2: Python Program to Count Occurrence of a Specific Character in a String Using While Loop

Python Program to Count Occurrence of a Specific Character in a String Using While Loop

# Python Program to Count Occurrence of a Specific Character in a String Using While Loop

# Take the Input From the User
string = input("Enter The String: ")
char = input("Enter The Character: ")
i = 0
count = 0

while(i < len(string)):
    if(string[i] == char):
        count = count + 1
    i = i + 1

print("The total Number of Times ", char, " has Occurred = " , count)
Output

Enter The String: Tutorials Rack is an Online Learning Website

Enter The Character: a

The total Number of Times  a  has Occurred =  4


Related Posts



Comments

Recent Posts
Tags