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

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

相关推荐
李少兄9 天前
解决OSS存储桶未创建导致的XML错误
xml·开发语言·python
就叫飞六吧9 天前
基于keepalived、vip实现高可用nginx (centos)
python·nginx·centos
shadon1789 天前
回答 如何通过inode client的SSLVPN登录之后,访问需要通过域名才能打开的服务
linux
Vertira9 天前
PyTorch中的permute, transpose, view, reshape和flatten函数详解(已解决)
人工智能·pytorch·python
小米里的大麦9 天前
014 Linux 2.6内核进程调度队列(了解)
linux·运维·驱动开发
学Linux的语莫9 天前
python基础语法
开发语言·python
匿名的魔术师9 天前
实验问题记录:PyTorch Tensor 也会出现 a = b 赋值后,修改 a 会影响 b 的情况
人工智能·pytorch·python
Ven%9 天前
PyTorch 张量(Tensors)全面指南:从基础到实战
人工智能·pytorch·python
mahuifa9 天前
PySide环境配置及工具使用
python·qt·环境配置·开发经验·pyside
华子w9089258599 天前
基于 SpringBoot+JSP 的医疗预约与诊断系统设计与实现
java·spring boot·后端