Beginner String Problems Python

Count Vowels in a String in Python

Count how many vowels a string contains in Python, first with a loop and then with set membership.

  • TimeO(n),
  • SpaceO(1) for the counter; O(n) for the lowercase copy made by lower()
  • Hints3
  • Read3 min
Quick answer

To count vowels in a string in Python, set count = 0, loop with for ch in text, and add 1 when ch in "aeiouAEIOU". For "CodeBegun" the count is 4. A shorter version is sum(1 for ch in text.lower() if ch in set("aeiou")). Both take O(n) time. Convert to lowercase first or list both cases, or capital vowels will be missed.

for loop over a stringThe in operatorSetsCounters and dictionaries
1

Problem statement

Write a Python program to count the vowels in a string. The vowels are a, e, i, o, u in upper or lower case. Every other character, including spaces and digits, is not counted.

For "CodeBegun" the output is 4 (o, e, e, u).

Input

A string text.

Output

The number of vowels in text.

Examples

Example 1
Inputtext = "CodeBegun"
Output4

C-o-d-e-B-e-g-u-n has o, e, e and u.

Example 2
Inputtext = "rhythm"
Output0

There is no a, e, i, o or u. y is not counted as a vowel here.

Constraints

  • 0 <= len(text) <= 10^5
  • Only the English vowels a, e, i, o, u count; y is treated as a consonant
2

Think before you code

Reveal the questions to ask yourself first
  • How do you look at a string one character at a time?
  • How can you check if one character is any of five vowels without five if conditions?
  • What should happen to capital letters like A and E?
3

Hints

Open one at a time — try again after each.
1 Hint 1
for ch in text: gives you each character in turn.
2 Hint 2
ch in "aeiouAEIOU" is True when ch is a vowel of either case.
3 Hint 3
Or call text.lower() once, then you only need to check "aeiou".
4

Approach

Reveal the step-by-step approach

Version 1: loop and a vowel string

  1. Set count = 0.
  2. For each character ch in the string, check ch in "aeiouAEIOU".
  3. If it is True, add 1 to count.
  4. Return count.

in on a string checks whether ch appears anywhere inside "aeiouAEIOU". That replaces a long chain like ch == "a" or ch == "e" or ....

Version 2: set membership

Put the vowels in a set: VOWELS = set("aeiou"). Checking ch in VOWELS on a set takes about the same time no matter how big the set is. For five vowels the speed difference is tiny, but the set version is the habit interviewers like to see, and it pairs well with text.lower() so you only list lowercase vowels.

Way to check Example Notes
Vowel string ch in "aeiouAEIOU" Simple, list both cases
Set ch in VOWELS after lower() Clean, fast lookup
Chain of == ch == "a" or ... Long and easy to get wrong
5

Dry run

Walk through the example step by step

text = "CodeBegun":

ch | in "aeiouAEIOU"? | count
---+----------------+------
C  | no             | 0
o  | yes            | 1
d  | no             | 1
e  | yes            | 2
B  | no             | 2
e  | yes            | 3
g  | no             | 3
u  | yes            | 4
n  | no             | 4

The function returns 4.

6

Solution

Reveal the full Python solution
solution.py
def count_vowels(text):
    count = 0
    for ch in text:
        if ch in "aeiouAEIOU":
            count += 1
    return count


for word in ["CodeBegun", "Hyderabad", "rhythm", "AEIOU aeiou"]:
    print(word, "->", count_vowels(word))

Output:

CodeBegun -> 4
Hyderabad -> 3
rhythm -> 0
AEIOU aeiou -> 10

The space in "AEIOU aeiou" is checked but not counted, so the answer is 10, not 11.

Count vowels in Python using a set

VOWELS = set("aeiou")


def count_vowels(text):
    count = 0
    for ch in text.lower():
        if ch in VOWELS:
            count += 1
    return count


def count_vowels_short(text):
    return sum(1 for ch in text.lower() if ch in VOWELS)


print(count_vowels("Programming in Python"))
print(count_vowels_short("Programming in Python"))
5
5

text.lower() makes a lowercase copy, so the set only needs five letters. The short version adds 1 for each character that passes the if. It is the same loop written on one line.

Count vowels and consonants in Python

A consonant is a letter that is not a vowel. Use isalpha() so spaces, digits and punctuation are not counted as consonants.

text = input("Enter a string: ")
vowels = consonants = 0
for ch in text.lower():
    if ch.isalpha():
        if ch in "aeiou":
            vowels += 1
        else:
            consonants += 1
print("Vowels:", vowels)
print("Consonants:", consonants)
Enter a string: Hello World 2026
Vowels: 3
Consonants: 7

"Hello World" has 10 letters: e, o, o are vowels and the other 7 are consonants. The digits and spaces are skipped.

Count each vowel separately

text = "Education is important"
counts = {}
for ch in text.lower():
    if ch in "aeiou":
        counts[ch] = counts.get(ch, 0) + 1
print(counts)
print("Total:", sum(counts.values()))
{'e': 1, 'u': 1, 'a': 2, 'i': 3, 'o': 2}
Total: 9

counts.get(ch, 0) returns 0 the first time a vowel is seen. The dictionary keeps vowels in the order they first appear. See Python dictionary for more on get().

The Java version is on count the vowels and consonants in a string. To delete vowels instead of counting them, see remove all vowels from a string.

TimeO(n), where n is the length of the string
SpaceO(1) for the counter; O(n) for the lowercase copy made by lower()
7

Review before the interview

Common mistakes

  • Checking only "aeiou" without calling lower(), so "A" and "E" are missed.
  • Counting every non-vowel as a consonant, including spaces and digits. Check isalpha() first.
  • Writing if ch == "a" or "e" or "i". The non-empty string "e" is always True, so every character is counted.
  • Using text.count("a") + text.count("e") + ... without lowercasing, which also misses capitals.

Edge cases to test

  • Empty string: the loop does not run and the count is 0.
  • No vowels, like "rhythm": the count is 0.
  • Only spaces or digits: the count is 0, and the consonant count should also be 0.
  • Letters with accents such as é are not in "aeiou", so they are not counted.

Interview follow-ups

  • How would you print the positions where vowels appear?
  • How would you find which vowel appears the most?
  • How would you count vowels in each word of a sentence separately?

Keep practising

Practising Python for interviews?

CodeBegun’s Python Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us