Q:

Python | Count vowels in a string

belongs to collection: Python String Programs

0

Given a string, and we have to count the total number of vowels in the string using python program.

Example:

    Input:
    Str = "Hello world"

    Output:
    Total vowels are: 3

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

# count vowels in a string 

# declare, assign string 
str = "Hello world"

# declare count 
count = 0

# iterate and check each character
for i in str:
	# check the conditions for vowels
	if( i=='A' or i=='a' or i=='E' or i=='e'
	or i=='I' or i=='i' or i=='O' or i=='o'
	or i=='U' or i=='u'):
		count +=1;
		
# print count
print "Total vowels are: ", count

Output

    Total vowels are:  3

Implement the program by creating functions to check vowel and to count vowels:

Here, we are creating two functions:

1) isVowel()

This function will take character as an argument, and returns True, if character is vowel.

2) countVowels()

This function will take string as an argument, and return total number of vowels of the string.

Program:

# count vowels in a string 

# function to check character
# is vowel or not 
def isVowel(ch):
    # check the conditions for vowels 
	if(ch=='A' or ch=='a' or ch=='E' or ch=='e'
	or ch=='I' or ch=='i' or ch=='O' or ch=='o'
	or ch=='U' or ch=='u'):
		return True
	else:
		return False

# function to return total number of vowels
def countVowel(s) :
	# declare count 
	count =0
	# iterate and check characters
	for i in str:
		if(isVowel(i) == True):
			count += 1 
	return count
	
# Main code 
# declare, assign string
str = "Hello world"

# print count 
print "Total vowels are: ", countVowel(str)

Output

    Total vowels are:  3

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python | Passing string value to the function... >>
<< Python | Print EVEN length words...