PythonMastery
Python programs · Strings · beginner

Count vowels in a string in Python

Count the vowels (a, e, i, o, u) in a sentence with a loop and the in operator, then count each vowel separately with a dictionary.

Go through the text one character at a time and add 1 to a counter each time the character is a vowel.

The program

python
text = input("Enter a sentence: ")
vowels = "aeiou"

count = 0
for ch in text.lower():
    if ch in vowels:
        count += 1

print(f"Number of vowels: {count}")

Typed in this example: Programming in Python is fun. Press Run to type your own.

output
Enter a sentence: Programming in Python is fun
Number of vowels: 7

How it works

Count each vowel separately

A dictionary can hold one counter per vowel. Start each one at 0, then add to the right one:

python
text = "Grace Hopper wrote the first compiler"
counts = {"a": 0, "e": 0, "i": 0, "o": 0, "u": 0}

for ch in text.lower():
    if ch in counts:
        counts[ch] += 1

for vowel, n in counts.items():
    print(vowel, n)
output
a 1
e 5
i 2
o 3
u 0

ch in counts checks the keys of the dictionary, so it works the same way as ch in "aeiou".

Learn the idea: Working with Strings, Loops: for, while, and the Pythonic Patterns