Given a string, and we have to count the total number of vowels in the string using python program.
给定一个字符串,我们必须使用python程序计算字符串中的元音总数。
Example:
例:
Input:
Str = "Hello world"
Output:
Total vowels are: 3
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()
1)isVowel()
This function will take character as an argument, and returns True, if character is vowel.
该函数将character作为参数,如果character是元音,则返回True 。
2) countVowels()
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
翻译自: https://www.includehelp.com/python/count-vowels-in-a-string.aspx