Python 我的代码怎么了?辅音

Python 我的代码怎么了?辅音,python,Python,==检查是否相等,这可能不是您想要的。必须使用in运算符来检查成员身份,在这种情况下,检查字符串中字符的成员身份。它遵循以下一般语法: def countConsonant (s): """Count consonants. 'y' and 'Y' are not consonants. Params: s (string) Returns: (int) #consonants in s (either case) """ # do not

==检查是否相等,这可能不是您想要的。必须使用in运算符来检查成员身份,在这种情况下,检查字符串中字符的成员身份。它遵循以下一般语法:

def countConsonant (s):

    """Count consonants.

    'y' and 'Y' are not consonants.

    Params: s (string)
    Returns: (int) #consonants in s (either case)
    """

    # do not use a brute force solution:
    # think of a short elegant solution (mine is 5 lines long);
    # do not use lines longer than 80 characters long

    # INSERT YOUR CODE HERE, replacing 'pass'
    countConsonant = 0
    for index in s:
        if index == 'bcdfghjklmnpqrstvwxyz':
            countConsonant += 1
    return countConsonant 

print (countConsonant ('"Carpe diem", every day.')) # should return 8
其中,x是操作数,或者如果y中存在成员身份,则是要检查的操作数。将其应用于本例,将if语句替换为:

if x in y:
然后检查特定字符是否在给定的辅音字符串中。还有一件事需要注意,您只检查小写。这意味着忽略了Carpe diem中的C,得到的结果是9。要忽略案例,请尝试:

if index in 'bcdfghjklmnpqrstvwxyz':
这将在检查语句时使字符串小写。

对于s中的索引:

您正在迭代s中的所有字符。那么情况呢

如果索引==“BCDFGHJKLMNPNPQRSTVWXYZ”:

ever计算toFalse,函数在所有情况下都返回0

要检查字符串中字符的成员身份,需要使用in运算符而不是==,这将检查值是否相等

如果算法与大小写无关,则可以将输入小写或将所有相应的大写字母添加到字符串“bcdfghjklmnpnpqrstvwxz”中。由于“y”和“y”不是符合要求的辅音,因此需要从字符串“bcdfghjklmnpnpqrstvwxyz”中删除y。最后的代码是

if index.lower() in 'bcdfghjklmnpqrstvwxyz':

寻求调试帮助的问题“为什么此代码不起作用?”必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参阅:。
def countConsonant (s):

    """Count consonants.

    'y' and 'Y' are not consonants.

    Params: s (string)
    Returns: (int) #consonants in s (either case)
    """
    countConsonant = 0
    for index in s.lower():
        if index in 'bcdfghjklmnpqrstvwxz':
            countConsonant += 1
    return countConsonant 

print (countConsonant ('"Carpe diem", every day.')) # should return 8