Skip to content
Home / Fundamentals

How to Count the number of Occurrences of a Character in a String in Python

In Python, there are several ways to count the number of occurrences of a character in a string. Here are some options:

Method 1: Using a for Loop

One way to count the number of occurrences of a character in a string is to use a for loop to iterate through the string and check if each character matches the character we are looking for. If it does, we can increment a counter. Here is an example:

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

string = "Hello, World!"
char = "l"
print(count_char_occurrences(string, char))  # Output: 2

Method 2: Using the count() Method

Another way to count the number of occurrences of a character in a string is to use the count() method of the string. This method returns the number of occurrences of a given substring in the string. Here is an example:

string = "Hello, World!"
char = "l"
print(string.count(char))  # Output: 2

Method 3: Using the collections.Counter() Function

If you want to count the number of occurrences of all characters in a string, you can use the collections.Counter() function. This function returns a dictionary with the characters as keys and the number of occurrences as values. Here is an example:

import collections

string = "Hello, World!"
char_counts = collections.Counter(string)
print(char_counts['l'])  # Output: 2

Method 4: Using a Dictionary

You can also use a dictionary to count the number of occurrences of a character in a string. First, create an empty dictionary. Then, use a for loop to iterate through the string and add each character to the dictionary as a key. If the character is already in the dictionary, increment the value for that key. Here is an example:

def count_char_occurrences(string, char):
    char_counts = {}
    for c in string:
        if c in char_counts:
            char_counts[c] += 1
        else:
            char_counts[c] = 1
    return char_counts[char]

string = "Hello, World!"
char = "l"
print(count_char_occurrences(string, char))  # Output: 2