How to count the total number of vowels in a string

Viewed 1343

Hi is there a better way of writing this code instead of writing the repetitive multiple if statements? I'm trying to find a better way of writing this code. Basically I want to count up the the total number of matching letters in the given string s.

s = 'abcdbobbobbegkhl'
count = 0
for letter in s:
    if letter == 'a':
        count += 1
    if letter == 'e':
        count += 1
    if letter == 'i':
        count += 1
    if letter == 'o':
        count += 1
    if letter == 'u':
        count += 1
print('Number of vowels: ' + str(count))
7 Answers

You can also use a list comprehension:

s = 'abcdbobbobbegkhl'
count = len([i for i in s if i in 'aeiou'])
print('Number of vowels: ' + str(count))
s = 'abcdbobbobbegkhl'
count = 0
for letter in s:
    if letter in 'aeiou':
        count += 1
print('Number of vowels: ' + str(count))

Or a one-liner:

count = sum(l in 'aeiou' for l in s)
s = 'abcdbobbobbegkhl'
count = 0
vowels = ['a','e','i','o','u']

for letter in s:
    if letter in vowels:
        count += 1

print('Number of vowels: ' + str(count))

Can be written in many ways. One of them is like :

for letter in s:
    if letter in ['a','e','i','o','u']:
        count = count+1
print('Number of vowels: ' + str(count))

Here is another solution, which may be nice:

s = 'abcdbobbobbegkhl'

vowels = 'aeiou'
count= 0

for vowel in vowels:
    count += s.count(vowel)

print('Number of vowels: ' + str(count))

Using a dict as the vocals set, you made direct access to vocals instead of to find in a list.

vocals = {'a':1,'e':1,'i':1,'o':1,'u':1}
s = "aeioutr"
count = 0
for letter in s:
  try:
    count+=vocals[letter]
  except KeyError:
    print(f"{letter} is not a vocal")
print(count) #5

OK, not exactly what was asked for, but might be useful anyway if the OP's goal is to count letter frequencies. This is using Counter to keep track of letter counts.

from collections import Counter

s = "I am a foobar and I have many vowels"

vowels = "aeiou"

vowels += vowels.upper()

counter = Counter(s)

sum_ = 0
for ch in vowels:
    sum_ += counter[ch]

print(f"Number of vowels:{sum_}")

Output:

Number of vowels:13
Related