Python統(tǒng)計字符串中英文字母、空格、數字和其它字符的個數
更新時間:2023年06月29日 10:09:08 作者:歡喜躲在眉梢里
這篇文章主要給大家介紹了關于Python統(tǒng)計字符串中英文字母、空格、數字和其它字符的個數的相關資料,本文實例講述了python統(tǒng)計字符串中指定字符出現次數的方法,需要的朋友可以參考下
輸入一行字符,分別統(tǒng)計出其中英文字母、空格、數字和其它字符的個數。
方法一:使用正則表達式
import re str1 = input("請輸入一行字符串:") alpha = 0 #英文字母 space = 0 #空格 digit = 0 #數字 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}中的英文字母個數為:{alpha}") print(f"{str1}中的空格個數為:{ space}") print(f"{str1}中的數字個數為:{digit}") print(f"{str1}中的其他字符個數為:{other}")
方式二:
while True: str1 = input("請輸入一行字符串:") alpha = 0 #英文字母 space = 0 #空格 digit = 0 #數字 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}中的英文字母個數為:{alpha}") print(f"{str1}中的空格個數為:{ space}") print(f"{str1}中的數字個數為:{digit}") print(f"{str1}中的其他字符個數為:{other}")
方式三:使用列表[]
while True: str1 = input("請輸入一行字符串:") alpha = [] #英文字母 space = [] #空格 digit = [] #數字 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}中的英文字母個數為:{len(alpha)}") print(f"{str1}中的空格個數為:{len(space)}") print(f"{str1}中的數字個數為:{len(digit)}") print(f"{str1}中的其他字符個數為:{len(other)}")
總結
到此這篇關于Python統(tǒng)計字符串中英文字母、空格、數字和其它字符個數的文章就介紹到這了,更多相關Python統(tǒng)計字符串個數內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python實現基于多線程、多用戶的FTP服務器與客戶端功能完整實例
這篇文章主要介紹了Python實現基于多線程、多用戶的FTP服務器與客戶端功能,結合完整實例形式分析了Python多線程、多用戶FTP服務器端與客戶端相關實現技巧與注意事項,需要的朋友可以參考下2017-08-08