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
String: Education is the key to opportunity a : 1 e : 3 i : 3 o : 4 u : 2 Total vowels: 13
How it works
- The dictionary
countsstarts with every vowel as a key and 0 as its value. text.lower()turns capitals into small letters, so "E" and "e" are counted together.if ch in countsis true only when the character is one of the five keys, and then that vowel goes up by one.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
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
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.
Related programs
- Count Vowels, Consonants, Uppercase and Lowercase Letters
- Remove Vowels from a String
- Check if a Character Is a Vowel or Consonant
- Count the Frequency of Each Character in a String
- Check a Palindrome String
- Reverse a String
- Generate a Random Password
- Count the Words in a String
- Remove Punctuation from a String
- Sort Words in Alphabetical Order
All Python programs · CBSE class 12 practical file · Python exercises