資訊內(nèi)容
Python基礎(chǔ)練習(xí)實(shí)例17(統(tǒng)計(jì)字符)
題目:輸入一行字符,分別統(tǒng)計(jì)出其中英文字母、空格、數(shù)字和其它字符的個(gè)數(shù)。
程序分析:利用 while 或 for 語(yǔ)句,判斷每一位字符string[i]是字母?數(shù)字?還是其它標(biāo)點(diǎn),用到isalpha、isspace、isdigit函數(shù)。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import string
s = raw_input('請(qǐng)輸入一個(gè)字符串:\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)
輸出結(jié)果:
請(qǐng)輸入一個(gè)字符串:
hello 123[]8**
char = 5,space = 1,digit = 4,others = 4
使用for循環(huán):
本站部分內(nèi)容轉(zhuǎn)載自網(wǎng)絡(luò),如有侵權(quán)請(qǐng)聯(lián)系管理員及時(shí)刪除。
