Python Program to Count the Number of Occurrences of a Character in a String – 2024

Hey guys, in this blog we will see a Python Program to Count the Number of Occurrences of a Character in a String.

Table of Contents

Example 1: Using a for loop

count = 0

my_string = "Machine Learning Projects"
my_char = "e"

for i in my_string:
    if i == my_char:
        count += 1

print(count)

Output

3

  • In this example we are traversing through each and every character of our string and checking if that character is equal to our char, we will increment the count number by 1.

Example 2: Using method count()

my_string = "Machine Learning Projects"
my_char = "e"

print(my_string.count(my_char))

Output

3

  • We can also simply use the count() method to count the number of instances of a character in a string.

Check out our other python programming examples

Leave a Reply

Your email address will not be published. Required fields are marked *