Algorithm
-
Input:
- Accept a string as input.
-
Initialize Counters:
- Initialize variables (counters) for each vowel (a, e, i, o, u) to zero.
-
Convert to Lowercase:
- Convert the input string to lowercase to handle both uppercase and lowercase vowels uniformly.
-
Iterate Through the String:
- Use a loop to iterate through each character in the string.
- Check for Vowels:
- For each character, check if it is a vowel (a, e, i, o, u).
-
Increment Counters:
- If the character is a vowel, increment the corresponding counter.
-
Display or Store Results:
- After processing the entire string, display or store the counts for each vowel.
Code Examples
#1 Code Example- Using Dictionary
Code -
Python Programming
# Program to count the number of each vowels
# string of vowels
vowels = 'aeiou'
ip_str = 'Hello, have you tried our tutorial section yet?'
# make it suitable for caseless comparisions
ip_str = ip_str.casefold()
# make a dictionary with each vowel a key and value 0
count = {}.fromkeys(vowels,0)
# count the vowels
for char in ip_str:
if char in count:
count[char] += 1
print(count)
Copy The Code &
Try With Live Editor
Output
{'o': 5, 'i': 3, 'a': 2, 'e': 5, 'u': 3}
#2 Code Example- Using a list and a dictionary comprehension
Code -
Python Programming
# Using dictionary and list comprehension
ip_str = 'Hello, have you tried our tutorial section yet?'
# make it suitable for caseless comparisions
ip_str = ip_str.casefold()
# count the vowels
count = {x:sum([1 for char in ip_str if char == x]) for x in 'aeiou'}
print(count)
Copy The Code &
Try With Live Editor
Demonstration
Python Programing Example to Count the Number of Each Vowel-DevsEnv