Python 统计一串字符里数字、英文字母、空格以及其他字符的个数

数字、英文字母、空格等其他字符在ASCII码表里有序号一一对应,可以利用ord函数来解决该问题:

ord() 函数是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值,如果所给的 Unicode 字符超出了你的 Python 定义范围,则会引发一个 TypeError 的异常。


在这儿首先想到要用到ASCII码,下面附一张ASCII码转换表:


0~9数字的ASCII码值取值范围为48~57

a~z小写英文字母的取值范围为97~122

A~Z大写英文字母的取值范围为65~90

sstr=list(input("Please enter a string: "))

alphas=[]
digits=[]
spaces=[]
others=[]

for i in range(len(sstr)):
	if ord(sstr[i]) in range(48,58):
		digits.append(sstr[i])
	elif ord(sstr[i]) in range(65,91) or ord(sstr[i]) in range(97,123):
		alphas.append(sstr[i])
	elif ord(sstr[i])==32:
		spaces.append(sstr[i])
	else:
		others.append(sstr[i])
print("The number of alpha is "+str(len(alphas))+".\n"
      +"The number of digit is "+str(len(digits))+".\n"
      +"The number of space is "+str(len(spaces))+".\n"
      +"The number of others is "+str(len(others))+".")


猜你喜欢

转载自blog.csdn.net/wxy_csdn_world/article/details/80741280