练习的内容已经在题目中体现了,接下来直接上两个程序和分析:
程序一:ascii 逆向操作
#统计一行字符的字母,空格,数字和其他字符
sentence = input("请输入一段字符:")
space = 0
digital = 0
letter = 0
other = 0
for i in sentence:
if ord(i) == 32:
space += 1
elif ord(i) <= 90 and ord(i) >= 65:
letter += 1
elif ord(i) <= 122 and ord(i) >= 97:
letter += 1
elif ord(i) <= 57 and ord(i) >= 48:
digital += 1
else:
other += 1
print("space:",space)
print("digtal:",digital)
print("letter:",letter)
print("other:",other)
程序二:函数isdigit()等检查
#统计一行字符的字母,空格,数字和其他字符
sentence = input("请输入一段字符:")
space = 0
digital = 0
letter = 0
other = 0
for i in sentence:
if i.isdigit():
digital += 1
elif i.isspace():
space += 1
elif i.isalpha():
letter += 1
else:
other += 1
print("space:",space)
print("digtal:",digital)
print("letter:",letter)
print("other:",other)
思维解析:
在得到正式算法前,犯了一个错误,认为函数isdigit()等只能检查数组中是否含有字母数字等,于是采用了ascii 逆向操作,当然,也是成功了的,就是,相当的麻烦。