【发布时间】:2022-01-04 17:58:16
【问题描述】:
我正在根据 NDev 的 YT 视频制作一个密码程序,出现的错误是索引超出范围,我是 python 新手,这是我的代码:
charToBin = {
"a":1,
"b":10,
"c":11,
"d":100,
"e":101,
"f":110,
"g":111,
"h":1000
}
binToWrd = {
1:"Intel",
10:"Info",
11:"Indipendent",
101:"Imposibble",
100:"Info-stolen",
110:"Indian-Ogres",
111:"Initially",
1000:"Infant-Orphan-Ogre-Ogle"
}
endTxt = " "
cipher = " "
def txtToBin():
global endTxt
txt = input(":")
txtArray = txt.split(" ")
for x in range(len(txt)):
endTxt += str(charToBin[txtArray[x]])+" "
print(endTxt)
def binToCip():
global cipher
codeTxtArr = endTxt.split(" ")
for x1 in codeTxtArr:
for x2 in binToWrd:
cipher += x1.replace(str(x2), binToWrd[x2])
print(cipher)
txtToBin()
binToCip()
我在输入中输入 b a d 时返回的错误:
Traceback (most recent call last):
File "main.py", line 41, in <module>
txtToBin()
File "main.py", line 30, in txtToBin
endTxt += str(charToBin[txtArray[x]])+" "
IndexError: list index out of range
【问题讨论】:
-
假设您输入了“b a d”。它的长度为 5。您将其拆分为长度为 3 的 txtArray,但您的
for循环使用len(txt),所以它仍然是 5。您不需要任何拆分的东西。我会在下面告诉你。 -
好的,我会检查的
标签: python arrays encryption indexing