jay
jay

Reputation: 11

Trying to create a function to return the total number of letters, uppercase, lowercase, numbers, and others, but can't seem to work - Python

def countCharacter(str):
    for i in str:
        letters = 0
        if i.isalpha():
            letters += 1
            
    for i in str:
        upper = 0
        lower = 0
        digit = 0
        others = 0
        if i.isupper():
            upper += 1
        elif i.islower():
            lower += 1
        elif i.isnumeric():
            digit += 1
        else:
            others += 1
            
    list = [letters, upper, lower, digit, others]
    return list
  
print(countCharacter("wh12p3cmaLKND;'$%^&*"))

Working on this function that is supposed to print a list of numbers of the respective characters, but don't seem to be working,

just learned python, need help please

Upvotes: 0

Views: 170

Answers (1)

U13-Forward
U13-Forward

Reputation: 71590

Try using the following code instead:

def countCharacter(string):
    letters = sum(i.isalpha() for i in string)
    upper = sum(i.isupper() for i in string)
    lower = sum(i.islower() for i in string)
    digit = sum(i.isdigit() for i in string)
    others = len(string) - sum([upper, lower, digit])
    return [letters, upper, lower, digit, others]
  
print(countCharacter("wh12p3cmaLKND;'$%^&*"))

Or to modify your original code:

def countCharacter(string):
    letters = 0
    for i in string:
        if i.isalpha():
            letters += 1

    upper = 0
    lower = 0
    digit = 0
    others = 0
    for i in string:
        if i.isupper():
            upper += 1
        elif i.islower():
            lower += 1
        elif i.isnumeric():
            digit += 1
        else:
            others += 1

    return [letters, upper, lower, digit, others]
  
print(countCharacter("wh12p3cmaLKND;'$%^&*"))

The reason your code doesn't work is because you're overriding the variables and setting them back to 0 on every iteration.

Upvotes: 1

Related Questions