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

程序分析:利用 while 或 for 语句,判断每一位字符string[i]是字母?数字?还是其它标点,用到isalpha、isspace、isdigit函数。

#!/usr/bin/python

# -*- coding: UTF-8 -*-

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)


输出结果:

请输入一个字符串:

hello 123[]8**

char = 5,space = 1,digit = 4,others = 4

使用for循环:

Python基础练习实例17(统计字符)


本站内容未经许可,禁止任何网站及个人进行转载。

   口袋儿题库-青少儿编程自测题库