用来练手的python 练习题其十三,原链接 : python练习实例17
题干 :
输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数
这个例题让我回忆起了远古的记忆,python str类的 isalpha,isspace,isdigit方法。这些方法通过比较ASCII码来判断输入的字符串对应的是哪一种字符,下面放出源代码:
def static_str():
number = 0
character = 0
space = 0
others = 0
my_string = input("输点字符:")
for i in my_string:
if i.isalpha():
character+=1
elif i.isspace():
space+=1
elif i.isdigit():
number+=1
else:
others+=1
affichage(number,character,space,others)
def affichage(number,character,space,others):
print("这个字符串中有%d个数字"%number)
print("这个字符串中有%d个字母"%character)
print("这个字符串中有%d个空格"%space)
print("这个字符串中有%d个其他字符"%others)
实验输出结果如下: