Python 練習實例17
題目:輸入一行字元,分別統計出其中英文字母、空格、數字和其他字元的個數。
程式分析:利用 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)
以上實例輸出結果為:
請輸入一個字串: 123zaixianc kdf235*(dfl char = 13,space = 2,digit = 6,others = 2