Write a Program to Count The Number of Occurrences of Character in a String in Python

Hi in this article you will learn about a Python program to count the number of times a character has occurred in a string.

Let's ask the user to enter the string and again ask the user to enter the character, try to use the for loop to iterate over the string and calculate the number of times a  character has occurred in the given string.


Write a Program to Count The Number of Occurrences of Character in a String in Python




Write a Program to Count The Number of Occurrences of Character in a String in Python

Take a text variable and use the input function call to ask a user to be interested,  take another variable named as char and use the input function call to ask the user to enter a character. Set the counter variable to zero,  this variable will be used to count the number of times a character as shown below.


text = input("Enter a String : ")
char = input("Enter a Character : ")
count = 0





Use the for loop to iterate all the letters present in the text variable and use the if statement to check if the letter is equal to care.  if the statement is true then increment the counter variable.  Once the for loop, the complete count variable will store the number of times a character has occurred in a string.

for letter in text:
   if letter == char:
       count += 1





Use the print function call to print the number of times a character has occurred in an even string,  by printing the count variable.

print("The Number of Occurrences of Character in a String is : ",count)



Complete Python Program
===============================

text = input("Enter a String : ")
char = input("Enter a Character : ")
count = 0

for letter in text:
   if letter == char:
       count += 1


print("The Number of Occurrences of Character in a String is : ",count)




Output 1
======================

Enter a String : oil dispenser
Enter a Character : z
The Number of Occurrences of Character in a String is :  0



Output 2
======================

Enter a String : playstation 5
Enter a Character : a
The Number of Occurrences of Character in a String is :  2




Output 3
===============

Enter a String : movies theaters
Enter a Character : e
The Number of Occurrences of Character in a String is :  3



Conclusion
=================

The above python script uses input function calls with the for loop and print function calls. It will accept the string, then process the string and display the Count of letters that occurred in the string.

Execute the above Python program by providing random string Input and random character to count into the string.

Comment it down below if you have any queries related to the above python script and not down the result.

Post a Comment

0 Comments