【Python 练习实例17】输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
解析:使用Python中的 isdigit() , isalpha() , isspace() 来判断字符是否是数字、字母或空格。
1 2 3 4 5 6 7 8 9 10 11 12 |
a = 'va gfabsf23r bf4er,v3 54v g45,.g3be vtrg34r.gwbwer' letter,digit,space,other = 0, 0, 0, 0 for i in a: if i.isdigit(): digit += 1 elif i.isalpha(): letter += 1 elif i.isspace(): space += 1 else: other += 1 print('letter:%d\ndigit:%d\nspace:%d\nother:%s' % (letter, digit, space, other)) |
输出:
1 2 3 4 |
letter:30 digit:11 space:5 other:4 |