Count Vowels in a String – Python

The task is to count the number of vowels (a, e, i, o, u) in a given string. Utilizing a set of vowels enhances the efficiency of membership testing, particularly with longer strings.

def count_vowels(s):
    return sum(1 for char in s.lower() if char in {'a', 'e', 'i', 'o', 'u'})

# Example usage
result = count_vowels("hello world")  # Output: 3

The implementation of the above code is as follow –

  • Function Definition: The function is defined with the name count_vowels and takes a single parameter s, which is expected to be a string.
  • Lowercase Conversions.lower() converts the entire string to lowercase, ensuring that the function is case-insensitive.
  • Generator Expression: The expression 1 for char in s.lower() if char in {'a', 'e', 'i', 'o', 'u'} generates a count of 1 for each vowel found in the string.
  • Return Statement: The sum function returns the total count of vowels.