Editor

Python Program to Count Each Vowel in a String

Beginner · Strings

This program counts how many times each vowel, a, e, i, o and u, appears in a string, instead of giving just one total. A dictionary holds one counter for each vowel, and capital and small letters are counted together.

Program

count_each_vowel.py
text = "Education is the key to opportunity" # or: text = input("Enter a string: ")
counts = {"a": 0, "e": 0, "i": 0, "o": 0, "u": 0}
for ch in text.lower():
if ch in counts:
counts[ch] += 1
print("String:", text)
for vowel, count in counts.items():
print(vowel, ":", count)
print("Total vowels:", sum(counts.values()))
Output
String: Education is the key to opportunity
a : 1
e : 3
i : 3
o : 4
u : 2
Total vowels: 13

How it works

  1. The dictionary counts starts with every vowel as a key and 0 as its value.
  2. text.lower() turns capitals into small letters, so "E" and "e" are counted together.
  3. if ch in counts is true only when the character is one of the five keys, and then that vowel goes up by one.
  4. sum(counts.values()) adds the five counts to give the total number of vowels.

Other ways to write it

Using count() in a dictionary comprehension

Using count() in a dictionary comprehension
text = "Education is the key to opportunity"
lower = text.lower()
counts = {vowel: lower.count(vowel) for vowel in "aeiou"}
print("Vowel counts:", counts)
Output
Vowel counts: {'a': 1, 'e': 3, 'i': 3, 'o': 4, 'u': 2}

The comprehension builds the same dictionary in one line: for each vowel it calls count(), which scans the whole string, so the string is read five times.

Using collections.Counter

Using collections.Counter
from collections import Counter
text = "Education is the key to opportunity"
letters = Counter(text.lower())
for vowel in "aeiou":
print(vowel, ":", letters[vowel])
Output
a : 1
e : 3
i : 3
o : 4
u : 2

Counter counts every character at once, and asking it for a character that never appeared gives 0 instead of an error.

Try it yourself

Show only the vowels that appear at least once by skipping any vowel whose count is 0.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises