Strings · beginner
Python Program to Count the Number of Vowels in a String
Count the vowels in a string in Python with a loop and a set, count each vowel separately with a dictionary, and do it in one line with sum().
- for loop over a string
- sets
- dictionaries
- str.casefold()
Counting vowels is a small exercise in looping over text and testing membership. The program counts all vowels, then counts each vowel separately with a dictionary.
The same pattern (loop over the characters, test each one, update a counter) works for counting digits, spaces, capital letters or any other group of characters, so it is worth understanding before reaching for a one-line shortcut.
The program
text = "Programming in Python is fun"
vowels = set("aeiou")
count = 0
per_vowel = dict.fromkeys("aeiou", 0)
for ch in text.casefold():
if ch in vowels:
count += 1
per_vowel[ch] += 1
print("Vowels:", count)
print(per_vowel)Vowels: 7
{'a': 1, 'e': 0, 'i': 3, 'o': 2, 'u': 1}How it works
- set("aeiou") makes a set of the five vowels. Checking ch in a set is fast and reads naturally.
- casefold() lowercases the text, so capital letters such as "O" are counted too. It is a stronger lower() for comparisons.
- dict.fromkeys("aeiou", 0) creates a dictionary with each vowel as a key and 0 as the starting count.
- For every vowel found, the total and that vowel's own count go up by one.
Watch it run line by line
Watch the per_vowel dictionary in the global frame: one count changes each time the highlighted line reaches count += 1.
“Visualize step by step” opens the program in the Python Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: One line with sum()
True counts as 1 in Python, so summing the results of the test counts the matches. collections.Counter counts every character at once.
from collections import Counter
text = "Programming in Python is fun"
print(sum(ch in "aeiou" for ch in text.lower()))
print(Counter(ch for ch in text.lower() if ch in "aeiou").most_common(2))7
[('i', 3), ('o', 2)]Common mistakes
- Forgetting to lowercase the text, so "A", "E", "I", "O" and "U" are not counted.
- Using text.count("aeiou"), which counts the five-letter sequence "aeiou", not individual vowels.
- Treating "y" inconsistently: decide whether it counts as a vowel for your task and say so.
- Accented vowels such as "é" are not in "aeiou". For text in other languages, decide whether to include them or normalize the text first with unicodedata.
Try it yourself
- Count consonants as well (letters that are not vowels; use ch.isalpha()).
- Remove all vowels from the sentence.
Open the program in the Python Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 Python examples, or write your own program in the online Python Compiler.