Python挑战练习-11
编写一个Python程序来计算字符串中元音字母的数量。
-
定义函数
vowel_count()
,参数为string
(表示字符串) -
在函数中统计字符串中的元音字母数,并返回计数
- 方法一:利用for循环
-
def vowel_count(string): # 此处写你的代码 vowels="aeiouAEIOU" count=0 for char in string : if char in vowels: count +=1 return count # 获取输入字符串 input_string = input() # 调用函数 print(vowel_count(input_string))
解释:
-
1.首先定义了一个包含所有元音字母(大小写形式)的字符串
vowels
-
2.
通过for char in string:
循环遍历入的字符串string
中的每一个字符。在循环中,使用if char in vowels:
判断当前字符char
是否在vowels
这个元音字母集合中,如果在,则说明该字符是元音字母,将count
的值加1
。