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.

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

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 517

Leave a Reply

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