方法1
# 输入一行字符串
str = str(input())
# 创建 alpha_num,digit_num,space_num,other_num记录字母、数字、空格、其他字符的个数
alpha_num = 0
digit_num = 0
space_num = 0
other_num = 0
# 循环判断字符串中每个字符的类型,并予以统计各类型字符的个数
for item in str:
if item.isspace():
space_num += 1
elif item.isalpha():
alpha_num += 1
elif item.isdigit():
digit_num += 1
else:
other_num += 1
# 输出各类型字符的个数
print("alpha: %i" %alpha_num)
print("digit: %i" %digit_num)
print("space: %i" %space_num)
print("other: %i" %other_num)
方法2:使用正则表达式匹配
import re
# 输入一行字符串
str1 = str(input())
# 使用 alpha_num,digit_num,space_num,other_num记录字母、数字、空格、其他字符的个数
alpha_num = len(re.findall('[A-Za-z]', str1))
digit_num = len(re.findall('[0-9]', str1))
space_num = len(re.findall(' ', str1))
other_num = len(str1)-alpha_num -digit_num - space_num
# 输出各类型字符的个数
print(f'alpha: %d' %alpha_num)
print(f'digit: %d' %digit_num)
print(f'space: %d' %space_num)
print("other: %i" %other_num)