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.
Python code
8 linesdef 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
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
- Use a dictionary comprehension or `collections.Counter` to get counts of each individual vowel.
- 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
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.