Home / Python / Example programs / Strings

Python program: Count vowels and consonants

Count the vowels, consonants, digits and spaces in a sentence.

The code

text = "Python 3 was released in 2008."
counts = {"vowels": 0, "consonants": 0, "digits": 0, "spaces": 0}
for ch in text.lower():
    if ch in "aeiou":
        counts["vowels"] += 1
    elif ch.isalpha():
        counts["consonants"] += 1
    elif ch.isdigit():
        counts["digits"] += 1
    elif ch == " ":
        counts["spaces"] += 1
print(counts)

Output

{'vowels': 7, 'consonants': 12, 'digits': 5, 'spaces': 5}

How it works

One pass through the text with if/elif sorts each character into a category; a dictionary keeps the counts together.

Python features used

Learn the ideas behind it in the free lesson Dictionaries & Sets.