且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

【python】编程语言入门经典100例--17

更新时间:2022-09-26 09:12:05

  1 #题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。


代码:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  2 
  3 li =list(input('输入一行字符:'))
  4 liletter = []
  5 linum = []
  6 lispace = []
  7 liother = []
  8 for in li:
  9     if str.isalpha(x) == True:
 10         liletter.append(x)
 11     elif str.isspace(x):
 12         lispace.append(x)
 13     elif str.isdigit(x) == True:
 14         linum.append(x)
 15     else:
 16         liother.append(x)
 17 print('这行字符串的英文字母有%d个,空格有%d个,数字有%d个,其它字符有%d个'%(len(liletter),len(lispace),len(linum),len(liother)))


运行结果:


1
2
3
4
5
6
7
8
9
10
[root@HK code_100]# python code_17.py 
输入一行字符:12 jkl*^hjk  &*^&*Hkjh 123123  fskldkl2354   ewrjlk234$
这行字符串的英文字母有23个,空格有9个,数字有15个,其它字符有8
[root@HK code_100]# python code_17.py 
输入一行字符:1 #  dfs  234 2k3r43yiuofds o9 sdf 
这行字符串的英文字母有17个,空格有10个,数字有9个,其它字符有1
[root@HK code_100]# python code_17.py 
输入一行字符:234jl 2134j oijo sf 08 @#&*jhjho &*^&*  (!@*!_)  234  dsfs
这行字符串的英文字母有18个,空格有12个,数字有12个,其它字符有16
[root@HK code_100]#


代码分析:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 # 这个不能用type(x) == type ('2')这种方式,因为将这一行字符转换成list后,list中的元素都是str类型,所以不能用这种方式.
  
  2 
  3 li =list(input('输入一行字符:'))         #接收输入的字符,转换成list
  4 liletter = []                            #建立需要使用的list
  5 linum = []
  6 lispace = []
  7 liother = []
  8 for in li:                           #遍历list
  9     if str.isalpha(x) == True:            # 如果这个字符是字母
 10         liletter.append(x)                # 添加到相应list
 11     elif str.isspace(x):                #如果这个字符是空格
 12         lispace.append(x)                # 添加到相应list
 13     elif str.isdigit(x) == True:        #如果这个字符是数字
 14         linum.append(x)                #添加到相应list
 15     else:                                #其余未匹配字符
 16         liother.append(x)                #添加到相应list
 17 print('这行字符串的英文字母有%d个,空格有%d个,数字有%d个,其它字符有%d个'%(len(liletter),len(lispace),len(linum),len(liother)))      #打印结果




      本文转自snc_snc 51CTO博客,原文链接:http://blog.51cto.com/netsyscode/1746776,如需转载请自行联系原作者