Python齐全字符串多维度统计九游会体育
任务条目
输入一转字符,输出以下五类统计效果:大写英翰墨母、小写英翰墨母、空格、数字、其他字符(如标点标志)。
任务分析
中枢逻辑
1.字符遍历:一一检查字符串中的每个字符。
2.类型判断:
内置本事:如isupper()、islower()、isdigit()、isspace()。ASCII码畛域:通过ord()函数将字符转为ASCII码,判断其所属区间。正则抒发式:哄骗re.findall()匹配特定款式。
3.计数统计:凭证判断效果累加计数器。
任求齐全
本事一:基础轮回法(内置函数)
def count_chars(text): upper = lower = digit = space = other = 0 for char in text: if char.isupper(): upper += 1 elif char.islower(): lower += 1 elif char.isdigit(): digit += 1 elif char.isspace(): space += 1 else: other += 1 return upper, lower, digit, space, othertext = input("请输入字符串:")u, l, d, s, o = count_chars(text)print(f"大写字母:{u}\n小写字母:{l}\n数字:{d}\n空格:{s}\n其他字符:{o}")
评释:
上风:逻辑直不雅,适宜入门者;奏凯使用内置函数,代码好像。时弊点:通过isupper()等本事判断字符类型,逐字符遍历时代复杂度为。
本事二:正则抒发式法
import redef count_by_regex(text): upper = len(re.findall(r'[A-Z]', text)) lower = len(re.findall(r'[a-z]', text)) digit = len(re.findall(r'\d', text)) space = len(re.findall(r'\s', text)) other = len(text) (upper + lower + digit + space) return upper, lower, digit, space, othertext = input("请输入字符串:")u, l, d, s, o = count_by_regex(text)print(f"大写字母:{u}\n小写字母:{l}\n数字:{d}\n空格:{s}\n其他字符:{o}")
评释:
上风:代码更紧凑,适宜处理复杂匹配法子;re.findall()一次性索求通盘匹配项。时弊点:\d匹配数字,\s匹配空格,[A-Za-z]辞别大小写字母。
本事三:字典映射法
def count_with_dict(text): counter = {'upper': 0, 'lower': 0, 'digit': 0, 'space': 0, 'other': 0} for char in text: if char.isupper(): counter['upper'] += 1 elif char.islower(): counter['lower'] += 1 elif char.isdigit(): counter['digit'] += 1 elif char.isspace(): counter['space'] += 1 else: counter['other'] += 1 return countertext = input("请输入字符串:")counter = count_with_dict(text)print(f"大写字母:{counter['upper']}\n小写字母:{counter['lower']}\n数字:{counter['digit']}\n空格:{counter['space']}\n其他字符:{counter['other']}")
评释:
彭胀性:可纯真添加更多统计类别(如标点标志),便于效果处理。适用场景:需要动态颐养统计维度的任务。
启动效果
从键盘上输入字符串“faf&(8346FJH37696 8 $&&623jhdfKGG”。
请输入字符串:faf&(8346FJH37696 8 $&&623jhdfKGG
大写字母:6
小写字母:7
数字:13
空格:2
其他字符:5
进度已收尾九游会体育,退出代码为 0
Powered by J9九游会 AG亚游官网 @2013-2022 RSS地图 HTML地图