資訊內容
Python基礎練習實例17(統計字符)
題目:輸入一行字符,分別統計出其中英文字母、空格、數字和其它字符的個數。
程序分析:利用 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循環:
本站部分內容轉載自網絡,如有侵權請聯系管理員及時刪除。
