Python判断字符类型

225 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

题目描述:

输入一行字符,输出其中空格、数字、中文字符、英文字符和其他字符的个数。

实现代码:

str=input("请输入一行字符:\n")
chinese=0
letters=0
space=0
digit=0
others=0
for c in str:
    if  c.isspace():
        space+=1
    elif c.isdigit():
        digit+=1
    elif c>=u'\u4e00' and c<=u'\u9fa5':#判断是否为中文字符
        chinese+=1
    elif c.isalpha():
        letters += 1
    else:
        others+=1
print('空格=%d,数字=%d,中文字符=%d,英文字符=%d,其他字符=%d'%(space,digit,chinese,letters,others))

运行演示:

在这里插入图片描述