
Python完毕字符串多维度统计体育游戏app平台
任务条件
输入一滑字符,输出以下五类统计效果:大写英笔墨母、小写英笔墨母、空格、数字、其他字符(如标点标记)。
任务分析
中枢逻辑
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
程度已限制体育游戏app平台,退出代码为 0