Python练习题7(统计不同字符数量):编写一个函数,分别统计出传入字符串参数(可能不只一个参数)的英文字母、空格、数字和其它字符的个数(比如:'hello world,123456,Ch

方法一:用内置方法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))

 

上一篇:转载-Python学习笔记之文件读写


下一篇:express+sequelize 做后台