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语句较多,代码可读性较差。

方法二:

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函数中,可读性稍弱一些。

方法三:

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

忧伤的玩不起

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值