用来练手的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)
实验输出结果如下:

本文介绍了一个Python练习题,旨在帮助初学者掌握如何使用Python的str类方法如isalpha(), isdigit()和isspace()来统计输入字符串中字母、数字、空格和其他字符的数量。通过实际编码实践,加深对字符串处理的理解。
1919

被折叠的 条评论
为什么被折叠?



