吸收键盘任意录入,分别统计大小写字母、数字及别的字符数目,打印输出。
(条记模板由python脚本于2024年11月02日 08:23:31创建,本篇条记得当熟悉python字符串并懂得根本编程技法的coder翻阅)
[size=5.8]【学习的细节是欢悦的历程】
- Python 官网:https://www.python.org/
- Free:大咖免费“圣经”教程《 python 完全自学教程》,不仅仅是底子那么简单……
地点:https://lqpybook.readthedocs.io/
自学并不是什么神秘的东西,一个人一辈子自学的时间总是比在学校学习的时间长,没有老师的时候总是比有老师的时候多。
—— 华罗庚
- My CSDN主页、My HOT博、My Python 学习个人备忘录
- 好文力荐、 老齐教室
吸收键盘任意录入 字符串统计 (统计大小写字母、数字及别的字符) 本文质量分:
【 97 97 97 】
本文地点: https://blog.csdn.net/m0_57158496/article/details/143445325
CSDN质量分查询入口:http://www.csdn.net/qc
目 录
◆ 字符串统计
我之前也写过一篇解“字符串统计”小题的学习条记:
- 练习:字符串统计(坑:f‘string‘报错)
地点:https://blog.csdn.net/m0_57158496/article/details/121723096
浏览阅读:5.5k
收藏:1
[table][/table]
1、题目描述
- 题目描述截屏图片
1、编写函数,吸收一个字符串,分别统计大写字母、小写字母、数字和别的字符的个数,并以元组形式返回效果。在主步伐调用该函数并输出。
【题目泉源于 CSDN 问答社区提问《字符串统计》】
回页目次
2、解题逻辑
- a. 一样平常采用变量计数器。为每个统计项设立变量初值置0,遍历字符串时累加相应变量。
- b. 字典key替代统计变量,用dict.get方法辅助累加其值。dict结构数据,代码更紧凑,操纵更顺畅,这是一样平常统计数据结构的“最佳方式”。
回页目次
3、 代码实现
3.1 变量统计
- def char_statistics(text: str) -> None:
- upper_count = 0
- lower_count = 0
- number_count = 0
- other_count = 0
- for char in text:
- if char.isupper():
- upper_count += 1
- elif char.islower():
- lower_count += 1
- elif char.isdigit():
- number_count += 1
- else:
- other_count += 1
- print(f"Upper case letters: {upper_count}")
- print(f"Lower case letters: {lower_count}")
- print(f"Numbers: {number_count}")
- print(f"Other characters: {other_count}")
- # 示例文本
- sample_text = "Hello World! 12345"
- # 调用函数进行统计
- char_statistics(sample_text)
复制代码 ai是采用的“变量输出”,如要符题,只需将统计数据“组建”成tuple对象,修改输出语句就可以。如:
- # 前面代码保持不变
- keys = ('upper_count',
- 'lower_count',
- 'number_count',
- 'other_count')
- counter = [(k, v) for k,v in zip(keys, (upper_count, lower_count, number_count, other_count))] # 列表解析式解析成“键-值”对列表
-
- # 原print() 代码不变
- return tuple(counter) # 列表转换成元组返回
- # 示例文本
- sample_text = "Hello World! 12345"
- # 调用函数进行统计
- print(f"\n\n元组统计结果:\n{char_statistics(sample_text)}\n") # 以接收返回值的方式调用函数
复制代码
3.2 sum(列表剖析)
列表剖析统计
- upper_count = sum([1 if char.isupper() else 0 for i in text])
- lower_count = sum([1 if char.islower() else 0 for i in text])
- number_count = sum([1 if char.isdigit() else 0 for i in text])
- other_count = len(text) - upper_count - lower_count - number_count
复制代码
3.3 sum(天生器剖析)
天生器剖析统计
- upper_count = sum(1 for char in text if char.isupper())
- lower_count = sum(1 for char in text if char.islower())
- number_count = sum(1 for char in text if char.isdigit())
- other_count = len(text) - upper_count - lower_count - number_count
复制代码 天生器剖析,代码更简洁且少占用内存。
3.4 字典统计
- 字典统计
字典统计的代码脚本,请今后翻大概直接选择文章目次“完备源码”跳转。
|