1. 程式人生 > >統計輸入任意的字符中中英文字母,空格和其他字符的個數 python

統計輸入任意的字符中中英文字母,空格和其他字符的個數 python

字符 -s dig digi else strong div dea 是否

這裏用到了三個函數:

#判斷是否為數字: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.

 

統計輸入任意的字符中中英文字母,空格和其他字符的個數 python