In Python, we can easily count how many vowels are in a string using a loop and counting the number of vowels we find in the string.
def countVowels(string):
count = 0
string = string.lower()
for char in string:
if char in "aeiou":
count = count + 1
return count
print(countVowels("Hello World!"))
#Output:
3
When working with strings, it can be useful to know how many vowels appear inside a variable.
In Python, we can easily get the count of vowels in a string looping over each character of the string and seeing if it is a vowel or not.
The vowels include “a”,”e”,”i”,”o”, and “u”.
Below is a function which will count the number of vowels for you in a string using Python.
def countVowels(string):
count = 0
string = string.lower()
for char in string:
if char in "aeiou":
count = count + 1
return count
print(countVowels("Hello World!"))
print(countVowels("This is a string with some words."))
print(countVowels("What's up?"))
#Output:
3
8
2
Counting the Number of Times Each Vowel Appears in a String Using Python
The example above is useful if you want to get the total number of vowels in a string. We can also use Python to get the count of how many times each vowel appears in a string.
To do this, we will loop over the vowels and create a dictionary which stores the count for each of the vowels.
Below is a function which will get the count of how many times each vowel appears in a given string.
def countEachVowel(string):
counts = {}
string = string.lower()
for vowel in "aeiou":
counts[vowel] = string.count(vowel)
return counts
print(countEachVowel("Hello World!"))
print(countEachVowel("This is a string with some words."))
print(countEachVowel("What's up?"))
#Output:
{'a': 0, 'e': 1, 'i': 0, 'o': 2, 'u': 0}
{'a': 1, 'e': 1, 'i': 4, 'o': 2, 'u': 0}
{'a': 1, 'e': 0, 'i': 0, 'o': 0, 'u': 1}
Hopefully this article has been useful for you to count the number of vowels in a string using Python.