如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
# -*- coding: utf-8 -*-
# 要求:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
def count(s):
count_a = count_z = count_o = count_s = 0
for i in s:
if ( ord (i)> = 97 and ord (i)< = 122 ) or ( ord (i)> = 65 and ord (i)< = 90 ):
count_a = count_a + 1
elif ord (i)> = 48 and ord (i)< = 57 :
count_z = count_z + 1
elif ord (i) = = 32 :
count_s = count_s + 1
else :
count_o = count_o + 1
print "英文字母个数:%d个" % count_a
print "数字个数:%d个" % count_z
print "其他字符个数:%d个" % count_o
print "空格个数:%d个" % count_s
if __name__ = = "__main__" :
s = raw_input ( "请输入一串字符:" )
count(s)
|
运行结果:
请输入一串字符:{""O: UIK YTJ ET_+*(_^*@#%@#$^#%*&456587978957FHSJHSRHFDHDFaHSHYWER YWERF R454qggsdhshrths
英文字母个数:48个
数字个数:15个
其他字符个数:22个
空格个数:7个
总结:
ord()将字符转换为ASCII码
以上这篇python统计字母、空格、数字等字符个数的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/Guo_Apple/article/details/69390107