輸入一行字符,分別統計出其中英文字母、空格、數字和其它字符的個數。
方法一:使用正則表達式
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統計字符串中英文字母、空格、數字和其它字符個數的文章就介紹到這了文章源自四五設計網-http://www.133122.cn/45986.html 文章源自四五設計網-http://www.133122.cn/45986.html
繼續閱讀
我的微信
微信掃一掃

我的微信
惠生活福利社
微信掃一掃

我的公眾號

評論