Python : Count the Number of Each Vowel

Tutorial by:Rizwan Abdullah      Date: 2016-06-16 02:20:17

Source Code

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

# string of vowels
vowels = 'aeiou'

# 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

```
Enter a string: Hello, have you tried our turorial section yet?
{'e': 5, 'u': 3, 'o': 5, 'a': 2, 'i': 3}
```

In this program we have take a string from the user. Using the method `casefold()` we make it suitable for caseless comparisions. Basically, this method returns a lowercased version of the string. 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.

We can do the same thing using a dictionary comprehension.

Source Code

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

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

Explanation

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.

Visit here to know more about list comprehension in Python or dictionary comprehension in Python.

Python

Submit Your Thought, Tutorial, Articls etc.