尝试使加密器将消息中每个字符的ascii值移位到密码输出中的相应字符的值总是会导致单个字符或字符串索引超出范围的错误:
msg = input()
pw = input()
pwN = 0
msgN = 0
for i in msg:
newmsg =""
nchar = chr(ord(msg[msgN]) + ord(pw[pwN]))
pwN += 1
msgN += 1
if pwN > len(pw):
pwN = 0
newmsg += nchar
print (newmsg)以这种形式运行它,在某些情况下会产生单个字符,而不是消息长度字符串,而在其他情况下会出现以下错误:
Traceback (most recent call last):
File "file", line 8, in <module>
nchar = str(chr(ord(msg[msgN]) + ord(pw[pwN])))
IndexError: string index out of range我不知道我错过了什么。
发布于 2020-12-10 19:15:30
问题是您在每个循环中将newmsg设置为空字符串。在for循环之前移动newmsg = ""应该可以解决单个字符的问题,尽管由于您在msg上迭代时手动增加了几个索引,因此很难计算出超出范围的错误。
我建议你看看Python提供的迭代特性。从技术上讲,您是在msg上迭代,但实际上从未使用过i,而是完全依赖于索引。一种更具pythonic风格的方法可能如下所示:
from itertools import cycle
msg = input()
pw = input()
newmsg = ""
for mchar, pwchar in zip(msg, cycle(pw)): # cycle loops the password so that abc becomes abcabcabc...
newmsg += chr(ord(mchar) + ord(pwchar))
print(newmsg)如果你想坚持循环。我甚至会使用一个生成器表达式来使它
from itertools import cycle
msg = input()
pw = input()
newmsg = "".join(chr(ord(mchar) + ord(pwchar)) for mchar, pwchar in zip(msg, cycle(pw)))
print(newmsg)https://stackoverflow.com/questions/65233181
复制相似问题