简体   繁体   中英

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

when I run the code it always shows 0 as results.... CODE:

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)

RESULT: the no of lower case: 0 the no of upper case 0 EXPECTED: the no of lower case:5 the no of upper case 5

我认为你需要使用char.islower()而不是string.islower()并且你可以做lower+=1而不是lower=lower+1upper

Your conditionals are incorrect. Update string.islower() and string.isupper() to char.islower() and char.isupper()

You need to iritate over each character indiviudaly. Now your program checks if whole string is written in uppercase or lowercase.

This means your code should look something like this:

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)

When comparing lower and higher value for your purpose you have to use "char" variable Like the example in this code

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM