python - 如何使函数检查字符串中有多少个辅音或元音?
问题描述
我正在上乔治亚理工学院的 CS1301xII 课程,我被这个问题难住了。我应该创建一个名为 count_letters 的函数。如果 find_consonants 为真,则计算辅音,如果为假,则计算元音。它应该只返回元音和辅音,不能返回大写字母、空格、数字或标点符号。我得到的输出是 0 个辅音,然后是 1 个元音。我预计是 14,然后是 7。
def count_letters(string, find_consonants):
if find_consonants == True:
count = 0
for i in string:
if i == ("q" or "w" or"r" or "t" or "y" or "p" or "s" or "d" or "f" or "g" or "h" or "j" or "k" or "l" or "z" or "x" or "c" or "v" or "b" or "n" or "m"):
count += 1
return count
else:
count = 0
for i in string:
if i == ("a" or "e" or "i" or "o" or "u"):
count += 1
return count
(下一节只是为了我自己测试,自动评分器更改字符串) a_string = "up with the white and gold"
print(count_letters(a_string, True))
print(count_letters(a_string, False))
解决方案
python中的or
操作是惰性求值,例如:
>>> ('a' or 'c')
'a'
>>> ('c' or 'b' or 'a')
'c'
所以i == ("a" or "e" or "i" or "o" or "u")
等价于i == 'a'
, 不是你想要的结果。
你可以像这样改变它
选项1
这太疯狂了……虽然
count = 0
for i in string:
if (i == "a") or (i == "e") or (i == "i") or (i == "o") or (i == "u"):
count += 1
选项2
这一款更优雅。
count = 0
for i in string:
if i in 'aeiou':
count += 1
选项3
这是Python
len([x for x in string if x in 'aeiou'])