Write a Python Program to Count the Number of Occurrence of a Character in String

As a Python programmer, it’s important to be able to efficiently count the number of occurrences of a particular character in a string.

Whether you’re working on a data analysis project or building a web application, this is a common task that you may encounter.

In this tutorial, we’ll walk through a simple Python program that counts the number of occurrences of a character in a string.


First, let’s define the problem. Given a string and a character, we want to count the number of occurrences of that character in the string.

For example, if the string is “hello world” and the character is “l”, we should get a count of 3, since there are three “l”s in the string.

To solve this problem, we’ll use a loop to iterate over each character in the string.

We’ll then use an if statement to check if the current character is equal to the character we’re looking for. If it is, we’ll increment a counter variable.

Finally, we’ll return the counter variable as the result.

Here’s the Python code to implement this program:

def count_occurrences(string, char):
    count = 0
    for c in string:
        if c == char:
            count += 1
    return count

Let’s break this down line by line.

First, we define a function called count_occurrences that takes two arguments: string and char.

This function will return the count of the number of occurrences of char in string.

Next, we initialize a counter variable called count to 0.

This variable will keep track of the number of occurrences of char.

We then use a for loop to iterate over each character in string.

The loop variable c takes on each character in turn.

Inside the loop, we use an if statement to check if c is equal to char.

If it is, we increment the count variable by 1.

Finally, after the loop has completed, we return the count variable as the result of the function.

To test our program, we can call the count_occurrences function with a string and a character.

Here’s an example:

string = "hello world"
char = "l"
count = count_occurrences(string, char)
print(count)  # Output: 3

In this example, we’re counting the number of occurrences of the letter “l” in the string “hello world”.

We pass these values as arguments to the count_occurrences function and store the result in the variable count.

Finally, we print the value of count, which should be 3.

That’s it!

With just a few lines of code, we’ve created a simple and efficient program to count the number of occurrences of a character in a string.