Reputation: 1
We want to know the index of the vowels in a given word, for example, there are two vowels in the word super (the second and fourth letters).
So given a string "super", we should return a list of [2, 4].
My Code:
def vowel_indices(word):
global vowels
global vowelsList
vowels = ["a" , "e" , "i" , "o" , "u" , "A" , "E" , "I" , "O" , "U"]
vowelsList = []
for letter in word:
if letter in vowels:
vowelsList.append(letter)
print(len(vowelsList))
vowel_indices("Anthony")
Instead of getting: 2, I'm getting: 1 2
Upvotes: 0
Views: 475
Reputation: 19816
As per your question's title, to find the number of vowels in a word, try the following:
len([l for l in word if l in 'aeiouAEIOU'])
In a function, it would be:
def vowels_number(word):
return len([l for l in word if l in 'aeiouAEIOU'])
Example of output:
>>> vowels_number('hello')
2
>>>
>>> vowels_number('world')
1
>>>
>>> vowels_number("Anthony")
2
To make your code works, this is what you can try:
vowels = 'aeiouAEIOU'
def vowels_number(word):
vowels_list = []
for letter in word:
if letter in vowels:
vowels_list.append(letter)
return len(vowels_list)
Output:
>>> vowels_number("Anthony")
2
Upvotes: 0
Reputation: 5714
Your code is almost okay just two things you got wrong.See below:
def vowel_indices(word):
global vowels
global vowelsList
vowels = ["a" , "e" , "i" , "o" , "u" , "A" , "E" , "I" , "O" , "U"]
vowelsList = []
for index,letter in enumerate(word):#add an index with enumerate
if letter in vowels:
vowelsList.append(index+1)#add 1 since list/arrays starts from 0
print(vowelsList)
vowel_indices("Super")
vowel_indices("anthony")
Output:
[2, 4]
[1, 5]
Upvotes: 0
Reputation: 15461
Try this:
>>> import re
>>> def vowel_indices(word):
>>> return len(re.findall('[aeiou]', word, re.IGNORECASE));
>>> print(vowel_indices("Anthony"));
2
Upvotes: 1
Reputation: 170153
If you want to return the indices of the vowels, than you should enumerate
the word.
vowelsList = [idx for idx, letter in enumerate(word) if letter in vowels]
Upvotes: 3