首页 > 解决方案 > 获取 TypeError:并非所有参数在字符串格式化期间都转换了 - 我知道错误在哪里,但我不明白如何纠正它

问题描述

for i in pass_tmp:
    if i % 2 == 0:
        t = ord(i)
        t = t + rot7
        rotated_7 = chr(t
        decrypted += i.replace(i, rotated_7)

    else:
        t = ord(i)
        t = t + rot9
        rotated_9 = chr(t)
        decrypted += i.replace(i, rotated_9)

return decrypted

我是 Python 的学习者,这是我在学习期间正在做的一个练习。

运行代码时,在引用代码中的“if i % 2 == 0:”行时,我收到以下错误消息“TypeError:并非所有参数都在字符串格式化期间转换”。

它可以正常工作,直到我添加“if i % 2 == 0:”行并添加了 else 代码块。我想要实现的是分离代码以进行不同的解码,这取决于 pass_tmp 的索引是偶数还是奇数,“如果 i % 2 == 0”应该处理,它在我之前的所有其他练习中都有效不得不使用它,但现在不是。

标签: python-3.x

解决方案


Ifpass_tmp是一个字符串,并且您可能需要以for i, char in enumerate(pass_tmp)这种方式使用的字符及其索引,i将是char您可以使用的索引和字符。它最终会是这样的:

for i, char in enumerate(pass_tmp):
    if i % 2 == 0:
        t = ord(char)
        t = t + rot7
        rotated_7 = chr(t)
        decrypted += char.replace(char, rotated_7)

    else:
        t = ord(char)
        t = t + rot9
        rotated_9 = chr(t)
        decrypted += char.replace(char, rotated_9)

return decrypted

您收到 typeError 是因为该操作i % 2 == 0试图获取将字符串除以整数的模数

此外,由于您一次迭代一个字符decrypted += i.replace(i, rotated_x)没有必要,您可以优化一点直接添加新变量decrypted += rotated_x,例如:

for i, char in enumerate(pass_tmp):
    if i % 2 == 0:
        t = ord(char)
        t = t + rot7
        rotated_7 = chr(t)
        decrypted += rotated_7

    else:
        t = ord(char)
        t = t + rot9
        rotated_9 = chr(t)
        decrypted += rotated_9

return decrypted

推荐阅读