Python Program to Count Repeated Characters in a String

1. Introduction

Identifying repeated characters in a string is a common task in text processing and analysis. This operation can be useful for various applications such as data validation, encryption, and compression algorithms. Python’s collection libraries and string methods offer efficient ways to count repetitions.

2. Program Steps

1. Define the string to be analyzed.

2. Create a dictionary to store the count of each character.

3. Iterate over the string, increasing the count for each character.

4. Filter out characters that occur only once.

5. Output the characters and their counts.

3. Code Program

# Define the string
input_string = "programming is fun"

# Initialize a dictionary to store the character counts
char_counts = {}

# Loop through each character in the string and count occurrences
for char in input_string:
    if char not in char_counts:
        char_counts[char] = 0
    char_counts[char] += 1

# Filter out characters that occur only once and print the rest
repeated_chars = {char: count for char, count in char_counts.items() if count > 1}
print("Repeated characters and their counts:")
for char, count in repeated_chars.items():
    print(f"'{char}': {count}")

Output:

Repeated characters and their counts:
'n': 2
'i': 2
'g': 2
' ': 2
'r': 2
'o': 2
'm': 2
's': 2

Explanation:

1. input_string holds the string to be checked for repeated characters.

2. char_counts is a dictionary that maps characters to their occurrence counts.

3. The for loop iterates through each char in input_string.

4. If char is not already a key in char_counts, it's added with an initial count of 0.

5. char_counts[char] is then incremented, reflecting the new count for char.

6. After counting, repeated_chars is created by a dictionary comprehension that filters char_counts to include only those characters with a count greater than 1.

7. The print loop iterates through repeated_chars, printing each character with its count of occurrences in input_string.

8. The characters and their counts are highlighted with backticks in the final printout to emphasize the code elements.

Comments