You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现字符统计字典时如何不将空格作为键计数?

字符计数跳过空格的修改方法

原代码核心计数逻辑没有问题,只是遍历字符时没有做过滤,导致空格键输入的空白也被纳入统计,只需增加空格过滤逻辑即可解决。

方法1:遍历过程中跳过空格

在循环内新增判断,当前字符为空格时直接跳过后续计数逻辑,对原有代码改动最小:

sentence = input("write a sentence: ")

d = dict()
for n in sentence:
    # 遇到空格直接跳过,不做计数
    if n == ' ':
        continue
    if n in d:
        d[n] += 1
    else:
        d[n] = 1
print(d)

方法2:预处理输入移除所有空格

拿到用户输入后先把字符串内的所有空格清除,再执行原有计数流程,不需要调整循环内部逻辑:

# 读取输入后直接替换掉全部空格字符
sentence = input("write a sentence: ").replace(' ', '')

d = dict()
for n in sentence:
    if n in d:
        d[n] += 1
    else:
        d[n] = 1
print(d)

扩展说明:如果需要同时过滤制表符、换行符等所有类型的空白字符,方法1里的判断条件可以替换为if n.isspace(): continue,即可覆盖所有空白场景。


内容的提问来源于stack exchange,提问作者Somebody

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 23:21:49