Python Program: Counting letters in a string
Python Counter Data Type: Exercise-1 with Solution
Write a Python program to create a 'Counter' of the letters in the string "Python Exercise!".
Sample Solution:
Code:
from collections import Counter
text = "Python Exercise!"
letter_counter = Counter(text)
print("Letter Counter:")
for letter, count in letter_counter.items():
if letter.isalpha():
print(f"{letter}: {count}")
Output:
Letter Counter: P: 1 y: 1 t: 1 h: 1 o: 1 n: 1 E: 1 x: 1 e: 2 r: 1 c: 1 i: 1 s: 1
In the exercise above "Counter" class from the "collections" module to count the occurrences of each letter in the given string. It then iterates through the items in the "Counter" and prints the counts of letters that are alphabetic characters.
Flowchart:
Previous: Python Extended Data Type Counter Exercises Home.
Next: Python Program: Counting common elements in a list.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/extended-data-types/python-extended-data-types-index-counter-exercise-1.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics