1、輸入一行字符,分別統(tǒng)計出其中英文字母、空格、數(shù)字和其它字符的個數(shù)。
方法一:使用正則表達式
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}")
?方式二:文章來源:http://www.zghlxwxcb.cn/news/detail-736318.html
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}")
?方式三:使用列表[]文章來源地址http://www.zghlxwxcb.cn/news/detail-736318.html
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)}")
到了這里,關于Python----統(tǒng)計字符串中的英文字母、空格、數(shù)字和其它字符的個數(shù)。的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!