题目
题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
分析
使用字符串string库。python3令人惊奇的是还可以定义中文变量,如代码2
实现
代码1
import string
s=input("请输入一个字符串:")
letter=0
space=0
num=0
other=0
for i in s:
if i.isalpha():
letter+=1
elif i.isspace():
space+=1
elif i.isnumeric():
num+=1
else:
other+=1
print("letter={},space={},num={},other={}".format(letter,space,num,other))
代码2
import string
s=input("请输入一个字符串:")
字母=0
空格=0
数字=0
other=0
for i in s:
if i.isalpha():
字母+=1
elif i.isspace():
空格+=1
elif i.isnumeric():
数字+=1
else:
other+=1
print("字母={},空格={},数字={},other={}".format(字母,空格,数字,other))