统计字符串里的字符数量
1、题目要求
输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数
2、程序分析
- 获取用户输入要使用raw_input函数
- 为了统计各种字符的数量,需要遍历字符串
- 对字符所属类型,字符串本身提供有很多方法
3、示例代码
#coding=utf-8
string = raw_input('input a string:\n')
char = 0
space = 0
digit = 0
others = 0
for item in string:
if item.isalpha():
char += 1
elif item.isspace():
space += 1
elif item.isdigit():
digit += 1
else:
others += 1
print "char={char} space={space} digit={digit} others={others}".format(char=char
,space=space,digit=digit,others=others)
4、字符串方法
- isalpha 判断是否为字母
- isspace 判断是否为空格
- isdigit 判断是否为数字