Python Program to Count Vowels in a String
Beginner Strings
Counts the vowels (a, e, i, o and u) in a string, capital letters included, by checking each character in turn.
The vowels in English are a, e, i, o and u. Counting them is a classic first string program: "Education" has 5, one of each (E, u, a, i, o), and "Rhythm" has none. The program goes through the text one character at a time and adds 1 for each vowel it finds.
Program
def count_vowels(text):
"""The number of vowels (a, e, i, o, u) in text."""
count = 0
for char in text.lower():
if char in "aeiou":
count += 1
return count
print("Vowels in Education:", count_vowels("Education"))
print("Vowels in Rhythm:", count_vowels("Rhythm"))
Open in the editor Download count_vowels.py
Output
Vowels in Education: 5
Vowels in Rhythm: 0
How it works
Step through the program line by line: each step below shows up as its line runs.
-
countstarts at 0. -
text.lower()is the text in lower case, so a capitalEbecomeseand the check below needs only the five lower-case vowels. The loop goes through it one character at a time. -
char in "aeiou"is true when the character is one of the five vowels (checking with in), and thencountgoes up by 1. Consonants, spaces and punctuation are skipped. - The function returns the total.
- "Education" has all five vowels, its capital E included. "Rhythm" has none, as
yisn't counted as a vowel.
For "Education", after lower():
char |
e | d | u | c | a | t | i | o | n |
|---|---|---|---|---|---|---|---|---|---|
count after it |
1 | 1 | 2 | 2 | 3 | 3 | 4 | 5 | 5 |
Other ways to write it
With sum()
sum() adds up a 1 for each vowel the generator expression finds, so the whole count fits in one line.
def count_vowels(text):
return sum(1 for char in text.lower() if char in "aeiou")
print(count_vowels("Programming in Python"))Counting each vowel
A dictionary comprehension (comprehensions) counts each vowel separately with the string
method count(), which gives how many times a character appears in a string.
def vowel_counts(text):
text = text.lower()
return {vowel: text.count(vowel) for vowel in "aeiou"}
print(vowel_counts("Programming in Python"))Try it yourself
- Count the vowels in a sentence of your own, and in the empty string
"". - Count the consonants instead: letters (
char.isalpha()) that aren't vowels. - Count
yas a vowel too, and check "Rhythm" again. - Collect the vowels in a list as well as counting them, and print the list.