Python | 计算字符串中的元音

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值