1.以简单的循环分支实现字符统计
str1 = input("输入字符串:") num=0;word=0;space=0;other=0; for i in str1: if i.isdigit(): num+=1 elif i.isalpha(): word+=1 elif i.isspace(): space+=1 else: other+=1 str2='''这段字符有%d个数字,有%d的字母,有%d个空格,其他字符有%d个'''%(num,word,space,other) print(str2)
2.以字典为载体,构造函数实现字符的统计
str1=input("请输入一段字符串:") def fun(s): dict1 = {"数字": 0, "字母": 0, "空格": 0, "其他": 0} for i in s: if i.isdigit(): dict1["数字"]+=1 elif i.isalpha(): dict1["字母"]+=1 elif i.isspace(): dict1["空格"]+=1 else: dict1["其他"] += 1 return dict1 print(fun(str1))