Python参考手册
Python 练习实例17
Python 练习实例17
Python 练习实例17
Python 100例题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
程序分析:利用 while 或 for 语句,条件为输入的字符不为 '\n'。
实例 - 使用 while 循环
#!/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)
实例 - 使用 for 循环
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import string
s = raw_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)
以上实例输出结果为:
请输入一个字符串: 123verydocc kdf235*(dfl char = 13,space = 2,digit = 6,others = 2Python 100例
Python 练习实例17 |
---|
Python 是一种面向对象的解释型计算机程序设计语言,由荷兰人 Guido van Rossum 于1989年发明,第一个公开发行版发行于1991年。 Python 是纯粹的自由软件, 源代码和解释器 CPython 遵循 GPL 协议。Python 语法简洁清晰,特色之一是强制用空白符( white space )作为语句缩进。
主页 | https://www.python.org/ |
源码 | https://github.com/python/cpython |
版本 | 2.7 |
发布版本 | 2.7.13 |