Python 練習實例17
python 練習實例17
題目:輸入一行字符,分別統(tǒng)計出其中英文字母、空格、數(shù)字和其它字符的個數(shù)。
程序分析:利用 while 或 for 語句,條件為輸入的字符不為 '\n'。
實例(python2.x) - 使用 while 循環(huán):
#!/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)
實例(python3.x) - 使用 for 循環(huán):
#!/usr/bin/python3 import string s = 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))
以上實例輸出結果為:
請輸入一個字符串: 123yapfc kdf235*(dfl char = 13,space = 2,digit = 6,others = 2