ToB企服应用市场:ToB评测及商务社交产业平台

标题: 字符串统计(Python) [打印本页]

作者: 西河刘卡车医    时间: 2024-11-3 21:31
标题: 字符串统计(Python)
吸收键盘任意录入,分别统计大小写字母、数字及别的字符数目,打印输出。
  
(条记模板由python脚本于2024年11月02日 08:23:31创建,本篇条记得当熟悉python字符串并懂得根本编程技法的coder翻阅)

   [size=5.8]【学习的细节是欢悦的历程】  


  自学并不是什么神秘的东西,一个人一辈子自学的时间总是比在学校学习的时间长,没有老师的时候总是比有老师的时候多。
            —— 华罗庚


   
  

   吸收键盘任意录入    字符串统计    (统计大小写字母、数字及别的字符)  

本文质量分:
                                                97                                      97                        97  
本文地点: https://blog.csdn.net/m0_57158496/article/details/143445325
CSDN质量分查询入口:http://www.csdn.net/qc

    目 录  
  

◆ 字符串统计


  我之前也写过一篇解“字符串统计”小题的学习条记:
[table][/table]

1、题目描述




题目泉源于 CSDN 问答社区提问《字符串统计》






   回页目次  

2、解题逻辑









   回页目次  

3、 代码实现


3.1 变量统计



  1. def char_statistics(text: str) -> None:
  2.     upper_count = 0
  3.     lower_count = 0
  4.     number_count = 0
  5.     other_count = 0
  6.     for char in text:
  7.         if char.isupper():
  8.             upper_count += 1
  9.         elif char.islower():
  10.             lower_count += 1
  11.         elif char.isdigit():
  12.             number_count += 1
  13.         else:
  14.             other_count += 1
  15.     print(f"Upper case letters: {upper_count}")
  16.     print(f"Lower case letters: {lower_count}")
  17.     print(f"Numbers: {number_count}")
  18.     print(f"Other characters: {other_count}")
  19. # 示例文本
  20. sample_text = "Hello World! 12345"
  21. # 调用函数进行统计
  22. char_statistics(sample_text)
复制代码
  ai是采用的“变量输出”,如要符题,只需将统计数据“组建”成tuple对象,修改输出语句就可以。如:
  1.     # 前面代码保持不变
  2.     keys = ('upper_count',
  3.             'lower_count',
  4.             'number_count',
  5.             'other_count')
  6.     counter = [(k, v) for k,v in zip(keys, (upper_count, lower_count, number_count, other_count))] # 列表解析式解析成“键-值”对列表
  7.    
  8.     # 原print() 代码不变
  9.     return tuple(counter) # 列表转换成元组返回
  10. # 示例文本
  11. sample_text = "Hello World! 12345"
  12. # 调用函数进行统计
  13. print(f"\n\n元组统计结果:\n{char_statistics(sample_text)}\n") # 以接收返回值的方式调用函数
复制代码

3.2 sum(列表剖析)


列表剖析统计
  1.     upper_count = sum([1 if char.isupper() else 0 for i in text])
  2.     lower_count = sum([1 if char.islower() else 0 for i in text])
  3.     number_count = sum([1 if char.isdigit() else 0 for i in text])
  4.     other_count = len(text) - upper_count - lower_count - number_count
复制代码

3.3 sum(天生器剖析)


天生器剖析统计
  1.     upper_count = sum(1 for char in text if char.isupper())
  2.     lower_count = sum(1 for char in text if char.islower())
  3.     number_count = sum(1 for char in text if char.isdigit())
  4.     other_count = len(text) - upper_count - lower_count - number_count
复制代码
天生器剖析,代码更简洁且少占用内存。

3.4 字典统计