用python3統計一行字元中的英文字母,空格,數字和其他字元的個數

snow_star_dream發表於2020-11-08

練習的內容已經在題目中體現了,接下來直接上兩個程式和分析:

程式一:ascii 逆向操作

#統計一行字元的字母,空格,數字和其他字元
sentence = input("請輸入一段字元:")

space = 0
digital = 0
letter = 0
other = 0

for i in sentence:
    if ord(i) == 32:
        space += 1
    elif ord(i) <= 90 and ord(i) >= 65:
        letter += 1
    elif ord(i) <= 122 and ord(i) >= 97:
        letter += 1
    elif ord(i) <= 57 and ord(i) >= 48:
        digital += 1
    else:
        other += 1
print("space:",space)
print("digtal:",digital)
print("letter:",letter)
print("other:",other)

程式二:函式isdigit()等檢查

#統計一行字元的字母,空格,數字和其他字元
sentence = input("請輸入一段字元:")

space = 0
digital = 0
letter = 0
other = 0

for i in sentence:
    if i.isdigit():
        digital += 1
    elif i.isspace():
        space += 1
    elif i.isalpha():
        letter += 1
    else:
        other += 1
        
print("space:",space)
print("digtal:",digital)
print("letter:",letter)
print("other:",other)

思維解析:
在得到正式演算法前,犯了一個錯誤,認為函式isdigit()等只能檢查陣列中是否含有字母數字等,於是採用了ascii 逆向操作,當然,也是成功了的,就是,相當的麻煩。

相關文章