How to Count Vowels in a String in Python

Counts uppercase and lowercase vowels in a given string using a set and a generator expression.

Easy Python 3.9+ Aug 9, 2026 Strings & text 12 views 0 copies

Python code

8 lines
Python 3.9+
def count_vowels(text):
    vowels = set("aeiouAEIOU")
    return sum(1 for char in text if char in vowels)

if __name__ == "__main__":
    sample = "Hello, World!"
    result = count_vowels(sample)
    print(f"Vowel count in '{sample}': {result}")

Output

stdout
Vowel count in 'Hello, World!': 3

How it works

The function creates a set of all vowel characters, both uppercase and lowercase, for fast membership testing. It then uses a generator expression that iterates over each character in the input text and yields 1 for each vowel. The built-in sum function adds up these 1s to produce the total vowel count. This approach is concise, efficient, and works with any string, including spaces and punctuation.

Common mistakes

  • Forgetting to include both uppercase and lowercase vowels in the set.
  • Using a list comprehension instead of a generator, which uses more memory for large inputs.
  • Counting 'y' as a vowel when the requirement specifies only a, e, i, o, u.

Variations

  1. Use a dictionary comprehension or `collections.Counter` to get counts of each individual vowel.
  2. Use a regular expression with `re.findall` to count vowels: `len(re.findall(r'[aeiouAEIOU]', text))`.

Real-world use cases

  • Analyzing text data to measure vowel frequency for linguistic or educational purposes.
  • Validating user input that must contain at least a certain number of vowels.
  • Preprocessing data for speech synthesis or phonetic analysis tools.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.