Count vowels in a string python using for loop

Python Code:

sentence = input('Enter a string:')
vowel = 'A,a,E,e,I,i,O,o,U,u'
Count = 0
for vowel in sentence:
   Count += 1
print('There are {} vowels in the string: \'{}\''.format(Count,sentence))

I am trying to write a program that prompts the user to enter a string. The program then returns the number of vowels in the string. However, the code just returns the number of letters, without regard for just giving back vowels.

asked Sep 25, 2017 at 3:13

Count vowels in a string python using for loop

8

You've defined a string of vowels, but are redefining the variable vowels in the loop.

I'd recommend defining a set of vowels, and then incrementing your counter based on an if check.

vowels = set('aeiou')  

counter = 0
for c in sentence.lower():
    if c in vowels:
        counter += 1

Here, the if c in vowels will return True if c is a vowel (that is, c belongs to the set of vowels stored in vowels).


You could improve this solution with a collections.Counter object:

from collections import Counter

c = Counter(sentence.lower())
counter = sum(c[v] for v in set('aeiou'))

Alternatively, you could use a list comprehension and count its length.

answered Sep 25, 2017 at 3:20

Count vowels in a string python using for loop

cs95cs95

344k84 gold badges633 silver badges680 bronze badges

3

I think the best way is to use a simple RegEx. The RegEx to match a vowel is [aeiou] (or [aeiouy] if you want to match "y" too).

You can use re.findall to find all occurences of a vowel in a sentence, use the re.IGNORECASE flag to ignore case.

>>> import re
>>> sentence = "my name is Jessica"
>>> len(re.findall(r'[aeiou]', sentence, flags=re.IGNORECASE))
6

The advantage of this solution is that you can extend it easily to add accentuated characters or other unicode character:

>>> import re
>>> sentence = "Dès Noël où un zéphyr haï me vêt de glaçons würmiens je dîne d’exquis rôtis de bœuf au kir à l’aÿ d’âge mûr & cætera !"
>>> len(re.findall(r'[aeiouyàâèéêëiïîöôüûùæœÿ]', sentence, flags=re.IGNORECASE))
41

answered Jan 18, 2019 at 20:18

Count vowels in a string python using for loop

Laurent LAPORTELaurent LAPORTE

20.5k5 gold badges54 silver badges95 bronze badges

You aren't checking anywhere if the letters in the sentence are vowels. The syntax for x in y: defines a loop over an iterable object (string, list etc.) where for each loop iteration, the variable x is set to the next element of that iterable.

Your line for vowel in sentence: is simply defining a loop, where vowel is assigned to each letter of the input sentence. Your previous declaration of vowel = ... has no effect here.

A decent 1-liner to achieve the desired outcome would be:

sentence = input('Enter a string:')
vowels = 'aeiou'
count = len([c for c in sentence.lower() if c in vowels])

answered Sep 25, 2017 at 3:20

DBrowneDBrowne

6444 silver badges11 bronze badges

Using python 3:

sentence = input('Enter a string:')
vowels = 'A,a,E,e,I,i,O,o,U,u'
Count = 0
for each_char in sentence:
    if each_char in vowels:
        Count += 1 
print('There are {} vowels in the string: \'{}\''.format(Count,sentence))

answered Sep 25, 2017 at 3:21

Count vowels in a string python using for loop

Raju PittaRaju Pitta

5963 silver badges5 bronze badges

2

This is my code using Counter of collections

import collections
vowel = ['a', 'e', 'i', 'o', 'u']
count = 0

sentence = input('Enter a string:').lower()
counter = collections.Counter(sentence)
for word in counter:
    if word in vowel:
        count += counter[word]

print('There are {} vowels in the string: \'{}\''.format(count,sentence))

answered Sep 25, 2017 at 3:26

1

sentence = input('Enter a string:')
Count = 0
for eachLetter in sentence:
    if eachLetter.lower() in ['a','e','i','o','u']:
        Count += 1
print('There are {} vowels in the string: \'{}\''.format(Count,sentence))

answered Sep 25, 2017 at 3:27

1

We only need lowercase vowels in a list because we turn the sentence into lowercase only with .lower()

Then we loop through each vowel and count how many of each vowel is found in the sentence with .count(). Then we aggregate the total Count until we end up with the total number of vowels.

sentence = 'This is a sentence'
vowels = ['a','e','i','o','u']
Count = 0
for vowel in vowels:
    Count = Count + sentence.lower().count(vowel)

answered Sep 25, 2017 at 3:29

Michele87Michele87

311 silver badge3 bronze badges

3

No need to make this difficult, even with the for loop constraint:

VOWELS = 'aeiou'

sentence = input('Enter a string: ')

count = 0

for letter in sentence.lower():
    count += letter in VOWELS

print('There are {} vowels in the string: \'{}\''.format(count, sentence))

The heart of this is that booleans are also numbers that we can sum. You can make VOWELS a set('aeiou') if you'll be processing lots of text and need added efficiency. We can replace the count initialization and for loop with a generator expression:

count = sum(1 for c in sentence.lower() if c in VOWELS)

This is likely better than a list comprehension as it doesn't create a throwaway list and avoids processing a subset of the letters a second time.

answered Sep 25, 2017 at 6:55

Count vowels in a string python using for loop

cdlanecdlane

38k5 gold badges27 silver badges74 bronze badges

That happens because you don't verify if the letter is a vowel. When you put 'vowel in sentence' on the for loop you just overwrites what is in vowel and vowel becomes each letter on sentence for each loop iteration.

sentence = input('Enter a string:')
vowel = 'A,a,E,e,I,i,O,o,U,u'
Count = 0
for letter in sentence:
  if letter in vowel.split(','):
    Count += 1
print('There are {} vowels in the string: \'{}\''.format(Count,sentence))

answered Sep 25, 2017 at 3:20

2

Not the answer you're looking for? Browse other questions tagged python or ask your own question.

How do you count the number of vowels in a string using for loop in Python?

Step 1: Take a string from the user and store it in a variable. Step 2: Initialize a count variable to 0. Step 3: Use a for loop to traverse through the characters in the string. Step 4: Use an if statement to check if the character is a vowel or not and increment the count variable if it is a vowel.

How do you count a string in a for loop in Python?

Use a for loop to count how many times the letter 'a' appears in the string 'fanta'. Check your answer using Python's string method called count()..
I guess you haven't understood the for loop. ... .
Nope, for loops are new to me. ... .
for x in l: overwrites any previous value of x while in the loop..

How do you check a vowel in a string Python?

We use re. findall() method to find all the vowels in string make list with them. We use len on list to find total vowels in string.

How do you count the number of vowels in a list in Python?

Python: Counting Vowels from List.
Merge list elements into a single string..
Create a loop that tests if a string element is a vowel..
Use a counter variable to keep track of vowels in string..
Print the value of the counter variable when finished with loop..