简体   繁体   中英

How to find the number of vowels in a string?

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

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]

Live example

Try this:

>>> import re
>>> def vowel_indices(word):
>>>   return len(re.findall('[aeiou]', word, re.IGNORECASE));
>>> print(vowel_indices("Anthony"));
2

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM