題目:
寫函數,計算傳入字符串中【數字】、【字母】、【空格] 以及 【其他】的個數
思路:
1、分別定義統計【數字】、【字母】、【空格] 以及 【其他】的變量,並初始化為0
2、遍歷傳入的字符串,判斷字符串內各字符的類型,並分別累加
3、輸出結果
代碼實現:
1 def count_str(strs): 2 """計算字符串中數字,字母,空格及其他的個數""" 3 # 【數字】、【字母】、【空格] 以及 【其他】初始化個數 4 int_count,str_count,spa_count,other_count = 0,0,0,0 5 for i in strs: # 遍歷字符串 6 if i.isdigit(): # 判斷是否為數字 7 int_count += 1 8 elif i.isalnum(): # 判斷是否為字母 9 str_count += 1 10 elif i.isspace(): # 判斷是否為空格 11 spa_count += 1 12 else: 13 other_count +=1 14 # 最后輸出 15 print("字符串s中,數字個數={},字母個數={},空格個數={},其他個數={}".format(int_count,str_count,spa_count,other_count)) 16 17 if __name__ == "__main__": 18 strs = input("請輸入字符串s:") 19 count_str(strs) # 調用函數