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库,如果不熟悉该库,理解起来可能较困难。

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

相关推荐
mouseliu1 分钟前
python之二:docker部署项目
前端·python
狂小虎19 分钟前
亲测解决self.transform is not exist
python·深度学习
Python智慧行囊20 分钟前
Python 中 Django 中间件:原理、方法与实战应用
python·中间件·架构·django·开发
HelloWord~28 分钟前
SpringSecurity+vue通用权限系统2
java·vue.js
让我上个超影吧28 分钟前
黑马点评【基于redis实现共享session登录】
java·redis
深科文库29 分钟前
构建 MCP 服务器:第 3 部分 — 添加提示
服务器·python·chatgpt·langchain·prompt·aigc·agi
yzx9910131 小时前
Linux 系统中的算法技巧与性能优化
linux·算法·性能优化
fengyehongWorld1 小时前
Linux Docker的简介
linux·docker
蓝婷儿1 小时前
6个月Python学习计划 Day 17 - 继承、多态与魔术方法
开发语言·python·学习