Python基础-判断类型统计个数

写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数

首先我们定义四个变量,分别存储数字、字母、空格、其他的数量

digital_temp = 0 # 存储数字个数
letter_temp = 0  # 存储字母个数
space_temp = 0   # 存储空格个数
other_temp = 0   # 存储其他个数

通过for循环遍历字符串s

 for i in s:
    if i.isdecimal():
        digital_temp += 1
    elif i.isalpha():
        letter_temp += 1
    elif i.isspace():
        space_temp += 1
    else:
        other_temp += 1

全部代码

def Count_str(s):
    digital_temp = 0
    letter_temp = 0
    space_temp = 0
    other_temp = 0
    for i in s:
        if i.isdecimal():
            digital_temp += 1
        elif i.isalpha():
            letter_temp += 1
        elif i.isspace():
            space_temp += 1
        else:
            other_temp += 1
    print('数字:%d\t字母:%d\t空格:%d\t其他:%d' % (digital_temp, letter_temp, space_temp, other_temp))

if __name__ == '__main__':

    s = input('请输入一串字符串:')
    Count_str(s)