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

Python TypeError: not all arguments converted报错修复求助

修复Python代码中的TypeError错误

你遇到的TypeError: not all arguments converted during string formatting错误,根源是这段代码:

for i in d.keys():
    print(i)
    if i % 2 == 0:

d的键是字符串类型(比如输入的字母、符号、数字字符),而%在Python中对字符串来说是格式化运算符,i % 2会被解析为用整数2格式化字符串i,但i里没有%d这类占位符,因此触发报错。

你的逻辑是想对字符在列表b中的索引值做奇偶判断,但现在循环的是字典的键(字符),不是索引值(字典的值)。


修复方案1:高效重构代码(推荐)

提前创建字符到索引的映射,直接遍历输入字符处理,避免冗余的嵌套循环和字典去重问题:

a = input("enter the message")
b = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
     "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
     ",", ".", "?", "!", "@", "#", "$", "%", "^", "&", "*",
     "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]

# 提前生成字符与索引的映射字典,替代嵌套循环查找
char_to_idx = {char: idx for idx, char in enumerate(b)}
result = ""

for char in a:
    # 获取字符对应的索引,不在列表中的字符保留原样
    idx = char_to_idx.get(char, None)
    if idx is None:
        result += char
        continue
    
    # 根据索引奇偶计算新索引
    if idx % 2 == 0:
        new_idx = idx // 2
    else:
        new_idx = (idx - 1) // 2
    
    # 根据新索引取对应字符
    result += b[new_idx]

print(result)

修复方案2:保留原代码结构修正

如果想保留原代码的大致结构,只需修改循环部分,正确获取索引值:

a = input("enter the message")
a = list(a)
b = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
     "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
     ",", ".", "?", "!", "@", "#", "$", "%", "^", "&", "*",
     "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
d = {}

for i in a:
    c = 0
    for j in b:
        if i == j:
            d[j] = c
        c = c + 1
print(d)

e = ""
# 遍历字典的键值对,拿到字符和对应的索引
for char, idx in d.items():
    print(char)
    if idx % 2 == 0:
        c = idx // 2
    else:
        c = (idx - 1) // 2
    # 直接通过索引取b中的字符,替代嵌套循环查找
    e += b[c]

print(e)

内容的提问来源于stack exchange,提问作者Tech by MI

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 16:53:31