Python Program to Count the Number of Each Vowel
In this example, we will write a program to take a string input from the user and count the number of each vowels in that given string. To better understand this example, make sure you have knowledge of the following tutorials:-
Contents
Python Program to Count the Number of Each Vowel using Dictionary
vowels = 'aeiou' input_str = input("Enter a string: ") # make it suitable for caseless comparisions input_str = input_str.casefold() # make a dictionary with each vowel a key and value 0 count = {}.fromkeys(vowels, 0) # count the vowels for char in input_str: if char in count: count[char] += 1 print(count)
The output of the above program is:-
Enter a string: This is a vowel counter program
{‘a’: 2, ‘e’: 2, ‘i’: 2, ‘o’: 3, ‘u’: 1}
{‘a’: 2, ‘e’: 2, ‘i’: 2, ‘o’: 3, ‘u’: 1}
Program Explanation:
Dictionary can be used to store the number of vowels with their count. The casefold() method converts all the characters in the input string into the same case, here it converts into small cases so that our program can effectively classify a and A as same vowel. Then we make a dictionary containing key as a vowel with initial value 0 using fromkeys() method. Finally, a for loop is used to iterate over each character and add to the vowel count if the character is present.
Python Program to Count the Number of Each Vowel using Strings
vowels = 'aeiou' input_str = input("Enter a string: ") # make it suitable for caseless comparisions input_str = input_str.casefold() # make a dictionary with each vowel a key and value 0 count = {}.fromkeys(vowels, 0) # count the vowels for char in input_str: if char in count: count[char] += 1 print(count)
The output of the above program is:-
Enter a string: This is a vowel counter program
{‘a’: 2, ‘e’: 2, ‘i’: 2, ‘o’: 3, ‘u’: 1}
{‘a’: 2, ‘e’: 2, ‘i’: 2, ‘o’: 3, ‘u’: 1}