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

Python如何统计字典字符串值的无空格长度并修复TypeError错误

错误原因分析

你修改后的代码存在4个核心问题:

  • 遍历字符串时for i in b得到的i是字符本身而非下标索引,直接用b[i]访问就会触发TypeError: string indices must be integers错误
  • 函数内使用return语句会直接终止执行,既无法遍历完所有字典键,也不能执行后续打印逻辑
  • strip()方法仅能移除字符串首尾的空格,无法处理字符串中间的空格,就算不报错也得不到正确的无空格长度
  • print语句放在了循环外层,只能打印最后一个键的结果,不符合遍历输出所有键的需求

解决方案

最简单的实现方式是直接把字符串中的所有空格替换为空后计算长度,代码如下:

def f(a):
    for key in a:
        # 替换所有空格为空后计算长度
        no_space_length = len(a[key].replace(' ', ''))
        print('{} {}'.format(key, no_space_length))

如果需要手动遍历字符实现统计,可参考以下代码:

def f(a):
    for key in a:
        count = 0
        for char in a[key]:
            if char != ' ':
                count += 1
        print('{} {}'.format(key, count))

测试用例a={'A': 'hey you', 'B': 'hello'}运行后即可得到预期输出:

A 6
B 5

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:57:03