首页 > 解决方案 > 试图创建一个函数来返回字母、大写、小写、数字等的总数,但似乎无法正常工作 - 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;'$%^&*"))

处理这个应该打印相应字符的数字列表但似乎不起作用的函数,

刚学python,求帮助

标签: python

解决方案


尝试改用以下代码:

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;'$%^&*"))

或者修改您的原始代码:

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;'$%^&*"))

您的代码不起作用的原因是因为您正在覆盖变量并将它们设置回0每次迭代。


推荐阅读