Reputation: 33
So I am very new to python and am in the process of learning the basics. I am trying to create a function the counts the number of vowels in a string and returns how many times each vowel occurs in the string. For example if I gave it this input, this is what it would print out.
>>>countVowels('Le Tour de France')
a, e, i, o, and u appear, respectively, 1,3,0,1,1 times.
I made this helper function to use, but then I'm not exactly sure how to use it.
def find_vowels(sentence):
count = 0
vowels = "aeiuoAEIOU"
for letter in sentence:
if letter in vowels:
count += 1
print count
And then I thought that maybe I could use formatting to get them in the write places, but I am not sure the notation that would be used for example, one of the lines for the function could be:
'a, , i, o, and u appear, respectively, {(count1)}, {(count2)}, {(count3)}, {(count4)}, {(count5)} times'
I am not sure how I would be able to fit the above in the function.
Upvotes: 1
Views: 16801
Reputation: 153
a =input("Enter string: ")
vowels = sum([a.lower().count(i) for i in "aeiou"])
print(vowels)
This also works. dont know if it is more or less efficient. it makes list for each of aeiou and sums it
Upvotes: 0
Reputation: 1251
An easier answer would be to use the Counter class.
def count_vowels(s):
from collections import Counter
#Creates a Counter c, holding the number of occurrences of each letter
c = Counter(s.lower())
#Returns a dictionary holding the counts of each vowel
return {vowel:c[vowel] for vowel in 'aeiou'}
Upvotes: 1
Reputation: 8845
You'd need to use a dictionary to store the values, since if you directly add the counts you lose information about exactly which vowel you are counting.
def countVowels(s):
s = s.lower() #so you don't have to worry about upper and lower cases
vowels = 'aeiou'
return {vowel:s.count(vowel) for vowel in vowels} #a bit inefficient, but easy to understand
An alternate method would be:
def countVowels(s):
s = s.lower()
vowels = {'a':0,'e':0,'i':0,'o':0,'u':0}
for char in s:
if char in vowels:
vowels[char]+=1
return vowels
to print this, you would do this:
def printResults(result_dict):
print "a, e, i, o, u, appear, respectively, {a},{e},{i},{o},{u} times".format(**result_dict)
Upvotes: 2