方法一:用内置方法isdigit()判断数字,isspace()判断空格,isalpha()判断字母,然后格式化输出
1 def str_count(msgs): 2 letter_count = 0 3 num_count = 0 4 space_count = 0 5 other_countd = 0 6 context = '' 7 str_sum = len(msgs) 8 for msg in msgs: 9 if msg.isdigit(): 10 num_count += 1 11 elif msg.isspace(): 12 space_count += 1 13 elif msg.isalpha(): 14 letter_count += 1 15 else: 16 other_count += 1 17 context = "该字符串有字母{letter}个,数字{num}个,空格{space}个,其他符号{other}个".format(letter = letter_count, 18 num = num_count, 19 space = space_count, 20 other = other_count) 21 return context 22 23 #msgs = 'hello world,123456,Change the world by program!' 24 msgs = input("请输入字符串:") 25 print(str_count(msgs))