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.
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