以下是Python代码实现:

def count_chars(s):
    num_count = 0
    letter_count = 0
    space_count = 0
    other_count = 0
    
    for char in s:
        if char.isdigit():
            num_count += 1
        elif char.isalpha():
            letter_count += 1
        elif char.isspace():
            space_count += 1
        else:
            other_count += 1
    
    return num_count, letter_count, space_count, other_count

使用示例:

s = "Hello 123 world!"
num_count, letter_count, space_count, other_count = count_chars(s)

print("数字个数:", num_count)
print("字母个数:", letter_count)
print("空格个数:", space_count)
print("其他字符个数:", other_count)

输出结果:

数字个数: 3
字母个数: 10
空格个数: 2
其他字符个数: 1
``
编写一个函数计算传入字符串中数字字母空格以及其他字符的个数

原文地址: https://www.cveoy.top/t/topic/fsbl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录