Python統(tǒng)計字符串中英文字母、空格、數(shù)字和其它字符的個數(shù)

輸入一行字符,分別統(tǒng)計出其中英文字母、空格、數(shù)字和其它字符的個數(shù)。

方法一:使用正則表達(dá)式

import re
str1 = input("請輸入一行字符串:")
alpha = 0  #英文字母
space = 0  #空格
digit = 0  #數(shù)字
other = 0  #其他
for i in str1:
#     print(i)
    if re.findall(r"[A-Za-z]",i):
        alpha += 1
    elif re.findall(r"\s", i):
        space += 1
    elif re.findall(r"\d",i):
        digit += 1
    else:
        other += 1
print(f"{str1}中的英文字母個數(shù)為:{alpha}")
print(f"{str1}中的空格個數(shù)為:{ space}")
print(f"{str1}中的數(shù)字個數(shù)為:{digit}")
print(f"{str1}中的其他字符個數(shù)為:{other}")

方式二:

while True:
    str1 = input("請輸入一行字符串:")
    alpha = 0  #英文字母
    space = 0  #空格
    digit = 0  #數(shù)字
    other = 0  #其他
    for i in str1:
        if i.isalpha():
            alpha += 1
        elif i.isspace():
            space += 1
        elif i.isdigit():
            digit += 1
        else:
            other += 1
    print(f"{str1}中的英文字母個數(shù)為:{alpha}")
    print(f"{str1}中的空格個數(shù)為:{ space}")
    print(f"{str1}中的數(shù)字個數(shù)為:{digit}")
    print(f"{str1}中的其他字符個數(shù)為:{other}")

方式三:使用列表[]

while True:
    str1 = input("請輸入一行字符串:")
    alpha = []  #英文字母
    space = [] #空格
    digit = []  #數(shù)字
    other = []  #其他
    for i in str1:
        if i.isalpha():
            alpha.append(i)
        elif i.isspace():
            space.append(i)
        elif i.isdigit():
            digit.append(i)
        else:
            other += 1
    print(f"{str1}中的英文字母個數(shù)為:{len(alpha)}")
    print(f"{str1}中的空格個數(shù)為:{len(space)}")
    print(f"{str1}中的數(shù)字個數(shù)為:{len(digit)}")
    print(f"{str1}中的其他字符個數(shù)為:{len(other)}")

到此這篇關(guān)于Python統(tǒng)計字符串中英文字母、空格、數(shù)字和其它字符個數(shù)的文章就介紹到這了文章源自四五設(shè)計網(wǎng)-http://m.wasochina.com/45986.html 文章源自四五設(shè)計網(wǎng)-http://m.wasochina.com/45986.html

繼續(xù)閱讀
我的微信
微信掃一掃
weinxin
我的微信
惠生活福利社
微信掃一掃
weinxin
我的公眾號
 

發(fā)表評論

匿名網(wǎng)友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

拖動滑塊以完成驗證