Python 字符统计:统计英文字符、数字、空格和其他字符
line = input('请输入一行字符:')
english_count = 0
digit_count = 0
space_count = 0
other_count = 0
for char in line:
if char.isalpha(): # 判断是否为英文字母
english_count += 1
elif char.isdigit(): # 判断是否为数字
digit_count += 1
elif char.isspace(): # 判断是否为空格
space_count += 1
else: # 其他字符
other_count += 1
print('英文字符个数:', english_count)
print('数字个数:', digit_count)
print('空格个数:', space_count)
print('其他字符个数:', other_count)
示例输出:
请输入一行字符:Hello 123 world!@#
英文字符个数: 10
数字个数: 3
空格个数: 2
其他字符个数: 3
原文地址: https://www.cveoy.top/t/topic/oDtE 著作权归作者所有。请勿转载和采集!