Python 练习实例17
题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
程序分析:利用while语句,条件为输入的字符不为'\n'。
程序源代码:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import string
s = raw_input('input a string:\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)
以上实例输出结果为:
input a string: runoob char = 6,space = 0,digit = 0,others = 0
Python 100例
健健
459878163@qq.com
Python3 下参考方案(可使用中文作为变量):
#!/usr/bin/python3 a = input('请输入一串字符:') 英文 = 0 空格= 0 数字= 0 其他= 0 for i in a: if i.isalpha(): 英文 += 1 elif i.isspace(): 空格 += 1 elif i.isnumeric(): 数字 += 1 else: 其他 += 1 print('英文 = %s,空格 = %s,数字 = %s,其他 = %s' % (英文,空格,数字,其他))健健
459878163@qq.com
等一个人
252343465@qq.com
Python3 下测试:
#!/usr/bin/env python3 InPut = input('输入任意字符:') letters = [] spaces = [] digits = [] others = [] for i in iter(InPut): if i.isalpha() == True: letters.append(i) elif i.isspace() == True: spaces.append(i) elif i.isdigit() == True: digits.append(i) else: others.append(i) print(''' 字母: {}, 个数: {}; 空字符: {}, 个数: {}; 数字: {}, 个数: {}; 其他: {}, 个数: {}'''.format(letters, len(letters), spaces, len(spaces), digits, len(digits), others, len(others)))等一个人
252343465@qq.com