Count Vowels in a String
In this problem, you will learn how to iterate through a string and use conditionals to check for specific characters. String manipulation and counting occurrences are common tasks in programming, especially when parsing text or analyzing user input.
Your objective is to write a function that accepts a string and returns the total number of vowels (A, E, I, O, U, both uppercase and lowercase) present in the string. You should initialize a counter, iterate over every character in the string, and increment the counter each time a vowel is encountered.
There are multiple ways to solve this. You can use a traditional for loop, or you can leverage Python's built-in sum() combined with a generator expression for a more compact and elegant solution.
Example 1:
Input: text = "Hello World"
Output: 3
Explanation: The vowels are 'e', 'o', and 'o'. Thus, the count is 3.
Example 2:
Input: text = "Programming is fun!"
Output: 5
Explanation: The vowels are 'o', 'a', 'i', 'i', 'u'.
Example 3:
Input: text = "XYZ"
Output: 0
Explanation: There are no vowels in the string, only consonants.
Constraints:
- The length of
textwill be between 0 and 10,000 characters. - The string may contain letters, spaces, numbers, and punctuation marks.
Algorithm Flow

Best Answers
def count_vowels(text):
# Approach 1: Generator expression
vowels = set('aeiouAEIOU')
return sum(1 for char in text if char in vowels)Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this problem.
