python-3.x - 获取 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”应该处理,它在我之前的所有其他练习中都有效不得不使用它,但现在不是。
解决方案
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
推荐阅读
- unit-testing - Kotlin 测试 API 调用
- angular - 如何对 Rxjs combineLatest 进行单元测试?
- spring - Spring boot Hibernate 多对多关系。传递给持久化的分离实体:
- azure - 使用 JDBC 从 Pyspark 更新表
- python-3.x - 谷歌日历 API 同步
- java - 取决于 OS 类型的条件 Spring 配置属性值
- flutter - 等价于 Flutter 中 CSS 的数值型 vertical-align
- php - 在 Laravel Collective 中为选择选项设置 ID
- php - 分页 php 不工作,卡在第一个,即使我回显存储页面数据的变量是正确的
- php - 如何在codeigniter中结合'foreach'和价值?