1. 程式人生 > 其它 >用Python統計字串個數

用Python統計字串個數

技術標籤:Pythonpython字串

1.題目

輸入一行字元,分別統計出其中英文字母、空格、數字和其它字元的個數。

2.程式分析

利用while語句,條件為輸入的字元不為’\n’.

from pip._vendor.distlib.compat import raw_input

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('字母個數 = %d,空格 = %d,數字 = %d,其他特殊字元 = %d' % (letters, space, digit, others))

在這裡插入圖片描述