In this article, we will discuss a Python program to count the number of each vowel in a given string. This program can be helpful in various applications where the analysis of vowels in a string is required, such as language processing and text analysis.
Before diving into the Python program, let us first understand vowels. Vowels are the letters A, E, I, O, U, and sometimes Y. In English, every word has at least one vowel. Now, let’s move on to the Python program.
string = "The quick brown fox jumps over the lazy dog"
vowels = 'aeiou'
# case-insensitive matching
string = string.lower()
# using dictionary comprehension to count the number of each vowel
count = {i: string.count(i) for i in vowels}
print(count)
In this program, we first define the input string and vowels we want to count. Then, we convert the input string to lowercase to perform case-insensitive matching. Finally, we use dictionary comprehension to count the number of each vowel in the string and print the result.
Defining the Input String and Vowels
The first step in the program is to define the input string and vowels we want to count. In this example, we have taken a sample string, “The quick brown fox jumps over the lazy dog”. We have also defined the vowels we want to count as ‘aeiou’. You can modify these values according to your requirements.
string = "The quick brown fox jumps over the lazy dog"
vowels = 'aeiou'
Converting the Input String to Lowercase
The second step in the program is to convert the input string to lowercase. This is done to perform case-insensitive matching. For example, if the input string contains uppercase vowels, we need to convert them to lowercase to match our defined vowels.
string = string.lower()
Counting the Number of Each Vowel
The final step in the program is to count the number of each vowel in the string. Again, we have used dictionary comprehension to achieve this. In dictionary comprehension, we iterate over the vowels and count the number of occurrences of each vowel in the input string using the count() method. The result is stored in a dictionary called count.
count = {i: string.count(i) for i in vowels}
Output:
{'a': 1, 'e': 3, 'i': 1, 'o': 4, 'u': 2}
This means that there is one occurrence of the letter ‘a’, three occurrences of the letter ‘e’, one occurrence of the letter ‘i’, four occurrences of the letter ‘o’, and two occurrences of the letter ‘u’ in the input string.
We have discussed a Python program to count the number of each vowel in a given string. We have explained each program step in detail, and we hope it will help you in your future programming endeavors.
Thanks for reading. Happy coding!