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

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

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
扎眼的阳光的头像扎眼的阳光普通用户
上一篇 2023年11月30日
下一篇 2023年11月30日

相关推荐