统计输入任意的字符中中英文字母,空格和其他字符的个数 python

这里用到了三个函数:

#判断是否为数字:str.isdigit()
#是否为字母:str.isalpha()
#是否为空格:str.isspace()
def tongji(str):
    alpha = 0
    number = 0
    space =0
    qt = 0
    for i in range(len(str)): #或者for i in str:
        if str[i].isalpha():  #接上一句改为:i.isalpha()
            alpha += 1
        elif str[i].isdigit():
            number += 1
        elif str[i].isspace():
            space += 1
        else:
            qt += 1
    print("中英文字母的个数为%i,数字的个数为%i,空格的个数为%i,其他字符的个数为%i." %(alpha,number,space,qt))
tongji("  12a deA F哈哈哈哈···")

运行结果:

中英文字母的个数为9,数字的个数为2,空格的个数为4,其他字符的个数为3.

 
posted @ 2018-11-02 21:44  RamboBai  阅读(720)  评论(0编辑  收藏  举报