Counting Vowels in a String – Python

From this project.

The Challenge

Enter a string and the program counts the number of vowels in the text. For added complexity have it report a sum of each vowel found.

The Logic

Make a dictionary with the vowels as keys. Then loop through each letter in the string. If it’s a vowel, append it to the relevant list. Then find the length of that list to see how many there are.

The Code

# dictionary with vowels as keys and a list as its value
dict_vowels = {'a':[],

# this is the test string
str_test_raw_string = raw_input('Enter String: ')

# all to lower case
str_test_string = str_test_raw_string.lower()

# check each character...loop
# take each letter in the string
for str_each_letter in str_test_string:
    # if the letter is in the dictionary
    if str_each_letter in dict_vowels:
        # append it to the dictionary entry
# sorted dict for alphabetical order
dict_sorted = sorted(dict_vowels)

# print rtesults
for i in dict_sorted:
    print i,len(dict_vowels[i])

So if we run the code

$ python
Enter String: Jose Christian

We should get the following output

a 1
e 1
i 2
o 1
u 0

EDIT: A different way of doing it

Instead of creating a list and then fining the length of the list, this will start with a 0 value for each vowel, and add 1 every time it finds it.

# input the string that will be used
str_raw_string = raw_input('Enter String: ')

# create the dictionary
dict_vowels = {'a':0,

# lower the string
for str_letter in str_raw_string.lower():
    if str_letter in dict_vowels:

# print in alphabetical order (sorted)
for str_vowel in sorted(dict_vowels):
    print str_vowel,dict_vowels[str_vowel]

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s