2020-12-10

输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。

import string
s = raw_input(‘请输入一个字符串:\n’)
letters = 0
space = 0
digit = 0
others = 0
i=0
while i < len(s):
c = s[i]
i += 1
if c.isalpha():
letters += 1
elif c.isspace():
space += 1
elif c.isdigit():
digit += 1
else:
others += 1
print ‘char = %d,space = %d,digit = %d,others = %d’ % (letters,space,digit,others)

  • 使用 for 循环

import string
s = input(‘请输入一个字符串:\n’)
letters = 0
space = 0
digit = 0
others = 0
for c in s:
if c.isalpha():
letters += 1
elif c.isspace():
space += 1
elif c.isdigit():
digit += 1
else:
others += 1
print (‘char = %d,space = %d,digit = %d,others = %d’ % (letters,space,digit,others))
以上输出结果为:
请输入一个字符串:
123runoobc kdf235*(dfl
char = 13,space = 2,digit = 6,others = 2

上一篇:031 实例7-七段数码管绘制


下一篇:习题 7-8 数字谜(Digit Puzzle, ACM/ICPC Xi‘an 2006, UVa12107)