Statement
Solution
Python Exercise 5.1: Character Counter
Use a dictionary to count how many times each character appears in a string.
Your program should:
- Ask the user for a string input.
- Create a dictionary where keys are characters and values are their counts.
- Print the character counts in a readable format.
- Handle both uppercase and lowercase characters (case-sensitive or insensitive, your choice).
Sample Interaction:
Input
Output
hello world
Enter a string: hello world
Character counts:
h: 1
e: 1
l: 3
o: 2
: 1
w: 1
r: 1
d: 1
Solution
Here is one way to solve this using a dictionary.
# Get input
text = input("Enter a string: ")
# Initialize dictionary
char_count = {}
# Count characters
for char in text:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
# Print results
print("Character counts:")
for char, count in char_count.items():
print(f"{char}: {count}")
Key Concepts:
- Dictionaries store key-value pairs, perfect for counting.
- Use
into check if a key exists. .items()returns key-value pairs for iteration.
Test Console
Run code to see output...