Count Number of Vowels using Sets in Given String - Python
Given a string, the goal is to count how many vowels it contains. Vowels include a, e, i, o, u (both uppercase and lowercase). For example:
Input: "Beautiful Day"
Output: 6
Explanation: Input has 6 vowels (e, a, u, i, u, a).
Let's explore different methods to count number of vowels in a given string in Python.
Using sum()
This method checks each character against a vowel set during a single pass through the string.
s = "Python is the best"
v = {'a','e','i','o','u','A','E','I','O','U'}
c = sum(1 for ch in s if ch in v)
print("Number of vowels:", c)
Output
Number of vowels: 4
Explanation:
- v holds vowels for quick membership testing.
- The generator 1 for ch in s if ch in v contributes a count whenever a vowel appears.
- sum() aggregates the total without creating extra lists.
Using casefold()
This method converts the whole string to a single case to reduce the vowel set and simplify comparisons.
s = "Python Programming"
v = {'a','e','i','o','u'}
s = s.casefold()
c = sum(1 for ch in s if ch in v)
print("Number of vowels:", c)
Output
Number of vowels: 4
Explanation:
- s.casefold() normalizes all characters for a uniform comparison.
- Using only lowercase vowels makes the set smaller.
Using count()
This method finds which vowels appear in the string, then counts their occurrences.
s = "Set operations in Python"
v = {'a','e','i','o','u','A','E','I','O','U'}
c = sum(s.count(ch) for ch in (set(s) & v))
print("Number of vowels:", c)
Output
Number of vowels: 8
Explanation:
- set(s) & v extracts only the vowel characters present in the string.
- s.count(ch) gives the frequency of each vowel.
- sum() adds all frequencies to produce the final count.
Using for loop (brute force)
We can create a set of vowels and iterate over the string and if the current character is present in the dictionary then increment the count of vowels.
vow = {'a','e','i','o','u','A','E','I','O','U'}
s = "This example uses brute force"
res = 0
for c in s:
if c in vow:
res+=1
print(res)
Output
10
Explanation:
- A set vow stores all vowels (both lowercase and uppercase).
- The string 's' is scanned character by character.
- For each character, if it's in the vowel set, the counter "res" is increased by 1.