Count Vowels in any String – Python way


The string is a collection of characters that are enclosed within the quotation marks. In the case of python, these quotations marks may be single/double/triple quotation marks. Unlike other programming language python assign index of any string from both sides. It assigns 0 indexes from left to right and -1 from right to left.

Using these indexes we can access individual elements of any string. The most common problem that we teach our students how to count vowels in string is – how to access each element of any string and compare them.

1. Count the total number of vowels

str1= "this is me and this is python class"
count=0
for x in str1:
  '''  if x =='a':
        count= count+1
    if x =='A':
        count = count+1
    if x=='e':
        count=count+1
    if x=='E':
        count=count+1
    if x=='i':
        count=count+1
    if x=='I':
        count=count+1
    if x=='o':
        count=count+1
    if x=='O':
        count=count+1
    if x=='u':
        count=count+1
    if x=='U':
        count=count+1   
  
 print('Total vowels :',count)

The above program is picking one character at a time and compare it with our vowels. But it is one the crudest method we ever have seen, the same program can be rewritten using logical operator OR

str1= "this is me and this is python class"
count=0
for x in str1:
  if x=='a'or x=='A' or x=='e' or x=='E' or x=='i' or x=='I' or x=='o' or x=='O' or x=='u' or x=='U':
        count = count+1   '''
print('Total vowels :',count)

again we are using the old age way to compare multiple values. Python does have a neat method to solve this type of value using the membership operator in. The next solution is the recommended way to do it in python.

str1= "this is me and this is python class"
count=0
for x in str1:
  if x in 'aAeEiIoOuU':
      count = count+1
        
print('Total vowels :',count)

Hope you would love these three simple solutions of counting vowels in any string, if you have any other method to solve this problem, let us know.

Print Friendly, PDF & Email

Related Posts

If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to contribute@cbsetoday.com See your article appearing on the cbsetoday.com main page and help other students/teachers.