Count Vowels From a String In Python Using Comprehension Method

Count Vowels From a String In Python Using Comprehension Method
(Last Updated On: 13/09/2022)

We know about the Count Vowels From a String In Python Using Comprehension Method, but in this article, we will help you to learn about Count Vowels From a String In Python Using Comprehension Method. Do you still face difficulties in understanding the logic? That’s perfectly fine; we have something more for you. You can scroll down to learn more about this topic.

For all the practice Videos and Explanations on Python, please click over here. Python Practice Series.

Program to Count Vowels From a String In Python Using Comprehension Method

string = "Python programming"
vowels = "AaEeIiOoUu"
final = [i for i in string if i in vowels]
print(len(final))
Output:
4

Code Explanation: Count Vowels From a String In Python Using Comprehension Method

This is really advanced and a little bit difficult to understand code; let’s kill this difficulty with learning. Here we have the same string as we have in previous programs. In the next line, we have a string of vowels containing both small and capital letters. Here we have initiated list comprehension. Let’s divide the code into 3 parts.

final = [i for i in string if i in vowels]

  • [i] 
  • for i in string
  • if i in vowels

Let’s understand this second part for i in string. Here we have started the interaction of the string with variable I. In the next part, if i is in vowels, we have checked if i is in vowels or not. Which is nothing but a simple condition. Now let’s come to the first part [I], which is the creation of a list with variable I. In simple terms, create a list with vowels from iteration through the string. Let’s run this, and you will get the result as 4.

If you want to learn python programming, you can refer to this Python Online Course with Certification. It’s easy to understand and meant for beginners who have no background in programming.