【问题标题】:gettting a TypeError: not all arguments converted during string formatting - I know where the error is but I don't understand how to correct it得到一个 TypeError: not all arguments convert during string formatting - 我知道错误在哪里,但我不明白如何纠正它
【发布时间】:2020-12-11 03:47:45
【问题描述】:
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”应该处理,它在我之前的所有其他练习中都有效以前用过,现在不用了。

【问题讨论】:

  • 你的pass_tmp是一个字符串吗?
  • 是的,它是一个字符串
  • 你认为'2'%2 打算做什么?字符串 %2 ? rotated_7 = chr(t 中的结束 ) 在哪里? minimal reproducible example 在哪里?

标签: python-3.x


【解决方案1】:

如果pass_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

【讨论】:

    猜你喜欢
    • 2019-10-10
    • 2020-03-19
    • 1970-01-01
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    相关资源
    最近更新 更多