python经典百题之统计字符数

题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。

方法一:

python 复制代码
str_input = input("请输入一行字符:")
count_letter, count_space, count_digits, count_other = 0, 0, 0, 0
for char in str_input:
    if char.isalpha():
        count_letter += 1
    elif char.isspace():
        count_space += 1
    elif char.isdigit():
        count_digits += 1
    else:
        count_other += 1
print("英文字母个数为:", count_letter)
print("空格个数为:", count_space)
print("数字个数为:", count_digits)
print("其他字符个数为:", count_other)

思路:使用for循环遍历字符串中的每一个字符,判断其属于英文字母、空格、数字还是其他字符,并记录相应个数。最后输出结果。

优点:简单易懂,代码量较少。

缺点:if-elif语句较多,代码可读性较差。

方法二:

python 复制代码
str_input = input("请输入一行字符:")
count_letter = sum(1 for char in str_input if char.isalpha())
count_space = sum(1 for char in str_input if char.isspace())
count_digits = sum(1 for char in str_input if char.isdigit())
count_other = len(str_input) - count_letter - count_space - count_digits
print("英文字母个数为:", count_letter)
print("空格个数为:", count_space)
print("数字个数为:", count_digits)
print("其他字符个数为:", count_other)

思路:使用生成器表达式与sum函数,将判断字符属于哪一类的过程集成到一行代码中,实现代码简洁化。

优点:代码量较少,可读性较好。

缺点:生成器表达式嵌套在sum函数中,可读性稍弱一些。

方法三:

python 复制代码
from collections import Counter

str_input = input("请输入一行字符:")
count_dict = Counter(str_input)
count_letter = count_dict.get("{}".format(chr(10))) - 1    # 减去回车符的个数
count_space = count_dict.get(" ")
count_digits = sum(1 for key in count_dict if key.isdigit())
count_other = len(str_input) - count_letter - count_space - count_digits
print("英文字母个数为:", count_letter)
print("空格个数为:", count_space)
print("数字个数为:", count_digits)
print("其他字符个数为:", count_other)

思路:使用Python标准库中的Counter计数器,将字符串中所有字符及其出现次数记录下来,然后通过字典的get方法获取英文字母、空格、数字及其他字符的数量。

优点:代码简洁,可读性较好。

缺点:需要导入collections库,如果不熟悉该库,理解起来可能较困难。

综上所述,三种方法都能实现统计英文字母、空格、数字和其他字符的个数,具体选择哪一种方法,主要取决于项目实际情况和个人喜好。

相关推荐
铁蛋Q5 分钟前
进程的状态
linux·服务器·ubuntu
零澪灵6 分钟前
ChartLlama: A Multimodal LLM for Chart Understanding and Generation论文阅读
论文阅读·python·自然语言处理·数据分析·nlp
极客小张22 分钟前
基于正点原子Linux开发板的智能监控与家电控制系统设计:深度解析Video4Linux和TCP/IP技术栈
linux·运维·c++·物联网·网络协议·tcp/ip·算法
sunxunyong23 分钟前
Linux 删除文件不释放空间问题处理
大数据·linux·运维·服务器
程序员小王꧔ꦿ23 分钟前
python植物大战僵尸项目源码【免费】
python·游戏
拓端研究室TRL24 分钟前
Python用TOPSIS熵权法重构粮食系统及期刊指标权重多属性决策MCDM研究|附数据代码...
开发语言·python·重构
一只特立独行的猪6111 小时前
Java面试——集合篇
java·开发语言·面试
只对您心动1 小时前
【C高级】有关shell脚本的一些练习
linux·c语言·shell·脚本
lldhsds1 小时前
linux下的分布式Minio部署实践
linux·minio·分布式对象存储
吃面不喝汤661 小时前
Flask + Swagger 完整指南:从安装到配置和注释
后端·python·flask