在 python 中查找字符串中大小写字母的个数

Finding the number of upper and lower case letter in a string in python

当我 运行 代码时,它总是显示 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的编号 预期的: 较低的编号 case:5 大写5的编号

我认为您需要使用 char.islower() 而不是 string.islower() 并且您可以使用 lower+=1 而不是 lower=lower+1 并且 upper[=15 也是如此=]

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

你需要对每个角色进行单独的激怒。 现在你的程序检查整个字符串是大写还是小写。

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

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)

当为了你的目的比较较低和较高的值时,你必须使用“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)