Python Program to Count the Number of Each Vowel

In this program, you'll learn to count the number of each vowel in a string using dictionary and list comprehension.

To understand this example, you should have the knowledge of following Python programming topics:

In the program below, we have taken a string stored in ip_str. Using the method casefold() we make it suitable for caseless comparisions. Basically, this method returns a lowercased version of the string.

Source Code: Using Dictionary

# Program to count the number of each vowel in a string

# string of vowels
vowels = 'aeiou'

# change this value for a different result
ip_str = 'Hello, have you tried our turorial section yet?'

# uncomment to take input from the user
#ip_str = input("Enter a string: ")

# 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)

Output

{'o': 5, 'i': 3, 'a': 2, 'e': 5, 'u': 3}

Note: To test this program, change the value of ip_str.

We use the dictionary method fromkeys() to construct a new dictionary with each vowel as its key and all values equal to 0. This is initialization of the count.

Next we iterate over the input string using a for loop.

In each iteration we check if the character is in the dictionary keys (True if it is a vowel) and increment the value by 1 if true.

Source Code: Using a list and a dictionary comprehension

# Program to count the number of
# each vowel in a string using
# dictionary and list comprehension

# change this value for a different result
ip_str = 'Hello, have you tried our turorial section yet?'

# uncomment to take input from the user
#ip_str = input("Enter a string: ")

# 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)

The ouput of this program is the same as above.

Here, we have nested a list comprehension inside a dictionary comprehension to count the vowels in a single line.

However, this program is slower as we iterate over the entire input string for each vowel.