你可以使用 Python 中的内置函数 isupper()、islower() 和 isnumeric() 来分别判断一个字符是否为大写字符、小写字符或数字字符,然后根据需要统计每种字符的个数。
下面是一个例子:
def count_chars(s):
# 定义一个列表,用于存储每种字符的个数
counts = [0, 0, 0, 0]
# 遍历字符串 s 中的每个字符
for c in s:
# 如果是大写字符,则将 counts[0] 加 1
if c.isupper():
counts[0] += 1
# 如果是小写字符,则将 counts[1] 加 1
elif c.islower():
counts[1] += 1
# 如果是数字字符,则将 counts[2] 加 1
elif c.isnumeric():
counts[2] += 1
# 否则,将 counts[3] 加 1
else:
counts[3] += 1
# 返回 counts 列表
return counts
# 调用函数并打印结果
print(count_chars('Hello, World!'))