在Python中查找字符串中的大小写字母的数量

时间:2020-11-10 17:16:06

标签: python string function uppercase lowercase

当我运行代码时,结果始终显示0...。 代码:

def case_counter(string):
    lower=0
    upper=0
    for char in string:  
        if (string.islower()):
            lower=lower+1
        
        elif (string.isupper()):
            upper=upper+1
        
    print('the no of lower case:',lower)
    print('the no of upper case',upper)
string='ASDDFasfds'        
case_counter(string)

结果: 小写数字:0 大写数字0 预期: 小写的数目:5 大写字母5的编号

4 个答案:

答案 0 :(得分:0)

我认为您需要使用char.islower()代替string.islower(),并且您可以使用lower+=1代替lower=lower+1,并且对upper也是一样

答案 1 :(得分:0)

您的条件不正确。将string.islower()string.isupper()更新为char.islower()char.isupper()

答案 2 :(得分:0)

您需要分别对每个字符进行说明。 现在,您的程序将检查整个字符串是大写还是小写。

这意味着您的代码应如下所示:

def upper_lower(text):
    upper = 0
    lower = 0
    for i in text:
        if i.isupper():
            upper += 1
        else:
            lower +=1
    print('the no of lower case:',lower)
    print('the no of upper case',upper)

答案 3 :(得分:0)

在比较较高和较低的值时,必须使用“ char”变量,如此代码中的示例一样

def case_counter(string):
    lower=0
    upper=0
    for char in string:  
        if (char.islower()):
            lower=lower+1
        
        elif (char.isupper()):
            upper=upper+1
        
    print('the no of lower case:',lower)
    print('the no of upper case',upper)
string='ASDDFasfds'        
case_counter(string)
相关问题