寫函數,計算傳入字符串中【數字】、【字母】、【空格] 以及 【其他】的個數
首先我們定義四個變量,分別存儲數字、字母、空格、其他的數量
digital_temp = 0 # 存儲數字個數 letter_temp = 0 # 存儲字母個數 space_temp = 0 # 存儲空格個數 other_temp = 0 # 存儲其他個數
通過for循環遍歷字符串s
for i in s: if i.isdecimal(): digital_temp += 1 elif i.isalpha(): letter_temp += 1 elif i.isspace(): space_temp += 1 else: other_temp += 1
全部代碼
def Count_str(s): digital_temp = 0 letter_temp = 0 space_temp = 0 other_temp = 0 for i in s: if i.isdecimal(): digital_temp += 1 elif i.isalpha(): letter_temp += 1 elif i.isspace(): space_temp += 1 else: other_temp += 1 print('數字:%d\t字母:%d\t空格:%d\t其他:%d' % (digital_temp, letter_temp, space_temp, other_temp)) if __name__ == '__main__': s = input('請輸入一串字符串:') Count_str(s)