用來練手的python 練習題其十三,原鏈接 : python練習實例17
題干 :
輸入一行字符,分別統計出其中英文字母、空格、數字和其它字符的個數
這個例題讓我回憶起了遠古的記憶,python str類的 isalpha,isspace,isdigit方法。這些方法通過比較ASCII碼來判斷輸入的字符串對應的是哪一種字符,下面放出源代碼:
def static_str():number = 0character = 0space = 0others = 0my_string = input("輸點字符:")for i in my_string:if i.isalpha():character+=1elif i.isspace():space+=1elif i.isdigit():number+=1else:others+=1affichage(number,character,space,others)def affichage(number,character,space,others):print("這個字符串中有%d個數字"%number)print("這個字符串中有%d個字母"%character) print("這個字符串中有%d個空格"%space)print("這個字符串中有%d個其他字符"%others)
實驗輸出結果如下: