Thursday, 06 February 2025

Count the number of occurrences of each character in a string in Python

Python 

This article demonstrates the use of dictionaries in Python through an example. It creates an empty dictionary to store characters from a string and their corresponding occurrence counts.

def count_characters(input_string):
    # Create an empty dictionary to store characters and their counts
    char_count = {}

    # Iterate over each character in the string
    for char in input_string:
        # If the character is already in the dictionary, increment its count
        if char in char_count:
            char_count[char] += 1
        # If the character is not in the dictionary, add it with a count of 1
        else:
            char_count[char] = 1

    # Return the dictionary of character counts
    return char_count

# Test string
input_string = "hello world"

# Call the function and print the result
result = count_characters(input_string)
print(result)

Output:

{'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}

Explanation:

  1. The count_characters function:

    • Takes a string input_string as input.
    • Uses a dictionary char_count to store each character and its occurrence count.
    • Iterates over each character in the string. If the character is already in the dictionary, its count is incremented; otherwise, the character is added to the dictionary with a count of 1.
  2. Test string:

    • The example string is "hello world"
  3. Output:

    • The program outputs a dictionary where the keys are characters and the values are their occurrence counts in the string.

Example breakdown:

For the string "hello world"

  • The character l appears 3 times.
  • The character o appears 2 times.
  • All other characters appear once.

You can replace input_string with any other string to calculate the occurrence counts of its characters.



Search