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


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co

Counting the number of occurrences of a character in a string involves iterating over each character in the string and checking if it matches the specified character. If it does, then the count is incremented.


Python Code :

The Below Python program that counts the number of occurrences of a character in a given string:


def count_character_occurrences(string, char):
    """
    Counts the number of occurrences of the given character in the given string.
    """
    count = 0
    for c in string:
        if c == char:
            count += 1
    return count

You can use this function by passing in a string and the character you want to count the occurrences of, like this:


count = count_character_occurrences('hello world', 'l')
print(count)

This will output the number of occurrences of the character ’l’ in the string ‘hello world’, which is 3:


3

If you want to count the occurrences of multiple characters, you can call this function multiple times with different characters. Alternatively, you can modify the function to take a list of characters and return a dictionary that maps each character to its count, like this:


def count_character_occurrences(string, chars):
    """
    Counts the number of occurrences of each character in the given string.
    Returns a dictionary that maps each character to its count.
    """
    counts = {}
    for char in chars:
        count = 0
        for c in string:
            if c == char:
                count += 1
        counts[char] = count
    return counts

You can use this modified function like this:


counts = count_character_occurrences('hello world', ['l', 'o'])
print(counts)

This will output a dictionary that maps the characters ’l’ and ‘o’ to their respective counts:


{'l': 3, 'o': 2}


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co