前面学习的都是Python的基础,所以前面的作业感觉相对简单。
题目:编写一个程序,输入一行字符,分别统计出其中的英文字母、空格、数字和其它字符的个数。
思路
- 定义四个变量,分别用来统计英文字母、空格、数字和其它字符的个数
- 逐个字符遍历输入的字符串,然后判断出是英文字符 or 空格 or 数字 or 其它字符,然后对应的统计变量加1
- 遍历完成后输出统计结果
代码
def charStatistic():
letterCount = 0 #统计英文字母的数量
spaceCount = 0 #统计空格的数量
numberCount = 0 #统计数字的数量
otherCount = 0 #统计其它字符的数量
strInput = str(input("please input a string:")) #提示用户输入一行字符
for ch in strInput: #遍历字符串
if (ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z'): #英文字母
letterCount += 1 #英文字母数量加1
elif ch >= '0' and ch <= '9': #数字
numberCount += 1 #数字数量加1
elif ch == ' ': #空格
spaceCount += 1 #空格数量加1
else: #其它字符
otherCount += 1 #其它字符数量加1
print("英文字母:%(letterCount)d,数字:%(numberCount)d,空格:%(spaceCount)d,其它字符:%(otherCount)d" %vars()) #输出统计结果
if __name__ == "__main__":
charStatistic()