定义帮助计数

2024-09-19 23:27:22 发布

您现在位置:Python中文网/ 问答频道 /正文

Define a function called count_engcons() which takes a string and returns the number of consonants in the string (uppercase or lowercase). For this problem, you may consider only letters in the English language alphabet only. Also, for this problem "Y" is considered a consonant (...not a vowel!). So for example count_engcons("Tessellated?") should return 7, and count_engcons("Aeiou!") should return 0. You must use a for loop, and you are not allowed to use the .count() method on this problem.

我试过这个:

def count_engcons(x):
    vowels = ("aeiou")
    count = 0

    for count_engcons in text:
        if not count_engcons in vowels:
            count += 1
    return x

但是,它会导致错误

谢谢Jornsharpe的否决票


Tags: andtheinyouonlyforstringreturn
1条回答
网友
1楼 · 发布于 2024-09-19 23:27:22

您正在检查一个字符是否不是元音,因此对于诸如!?之类的字符,它会给出不好的结果。您还试图使用不同的变量名(xtext)访问字符串,这是没有意义的

def count_engcons(text):
    consonants = "bcdfghijklmnpqrstvwxyz"
    count = 0

    for c in text.lower():
        if c in consonants:
            count += 1

    return count

相关问题 更多 >