1

I am a totally new programmer, learning python for the first time so sorry if my question isn't very clear and I am not using the correct computer science terminology. What I am trying to do is count the number of vowels in an inputed sentence without having to write out:

if i== 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u' or i == 'A' or i == 'E' or i == 'I' or i == 'O' or i == 'U'`

How do I check if the character char is inside the string 'aeiouAEIOU' using only one line? Could someone please tell me what am I doing wrong here?

This is my code so far.

def count_vowels (sentence):
    vowels = 0
    for char in sentence:
        if char == 'aeiouAEIOU'.split():
            vowels += 1
    return vowels
cs_newbie
  • 11
  • 2

2 Answers2

1

We can trim that down to something like:

Code:

def count_vowels(sentence):
    return sum(char in set('aeiouAEIOU') for char in sentence)

sum() is a quick way to add up sequences. This works because True is 1 and False is 0.

Test Code:

print(count_vowels('jkdbfjksdbvuihejsdvknweifn'))

Results:

5
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
0

Try replacing == with in and then check if the character is in the vowels:

def count_vowels (sentence):
    vowels = 0
    for char in sentence:
        if char in 'aeiouAEIOU':
            vowels += 1
    return vowels
print(count_vowels('Hello World!!!'))

Output:

3

Shorter Way

Try creating a list comprehension:

def count_vowels (sentence):
    return len([i for i in sentence if i in 'aeiouAEIOU'])
print(count_vowels('Hello World!!!'))

Output:

3
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • Is there an easier way to do it without using split() on the 'aeiouAEIOU' string and still maintaining only 1 line for the if statement? – cs_newbie Jun 03 '18 at 00:18
  • @RoryDaulton thanks for letting me know i edited my answer, i think now it's better – U13-Forward Jun 03 '18 at 00:21