- 题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
- 利用 while 或 for 语句,条件为输入的字符不为 ' '。
- 实例
1 import string 2 s = raw_input('请输入一个字符串: ') 3 letters = 0 4 space = 0 5 digit = 0 6 others = 0 7 i=0 8 while i < len(s): 9 c = s[i] 10 i += 1 11 if c.isalpha(): 12 letters += 1 13 elif c.isspace(): 14 space += 1 15 elif c.isdigit(): 16 digit += 1 17 else: 18 others += 1 19 print 'char = %d,space = %d,digit = %d,others = %d' % (letters,space,digit,others)
- 结果
1 I'm a monster 1wan 2he 3ying !!!
2 char = 19,space = 6,digit = 3,others = 4
- 利用for循环实现
- 代码
1 import string 2 s = input("请输入一个字符串: ") 3 letters = 0 4 space = 0 5 digit = 0 6 others = 0 7 for c in s: 8 if c.isalpha(): 9 letters += 1 10 elif c.isspace(): 11 space += 1 12 elif c.isdigit(): 13 digit += 1 14 else: 15 others += 1 16 print("char = %d,space = %d,digit = %d,others = %d" % (letters,space,digit,others))