gpt4 book ai didi

python - python中的索引错误

转载 作者:太空狗 更新时间:2023-10-30 01:55:15 24 4
gpt4 key购买 nike

我是编程新手,我正在尝试使用 Python 编写 Vigenère Encryption Cipher。这个想法非常简单,我的功能也是如此,但是在这一行中:

( if((BinKey[i] == 'b')or(BinKey[i+1] == 'b')): ) 

看来我有一个索引问题,我不知道如何解决它。错误信息是:

IndexError: string index out of range

我试图用另一个等于 i+1 的变量替换 i+1 索引,因为我认为 python 可能正在重新递增 i ,但还是不行。

所以我的问题是:

  1. 如何解决这个问题,我做错了什么?

  2. 看看我的代码,我可以学到什么来提高我的编程技能?

  3. 我想为我的程序构建一个简单的界面(它将包含所有加密密码),我从 Google 得到的只是 pyqt,但对于一个非常简单的界面来说似乎工作量太大了,那么有没有更简单的方法来构建接口(interface)? (我正在使用 Eclipse Indigo 和 pydev 以及 Python3.x)

Vigenère 加密函数(包含导致问题的行)是:

def Viegner_Encyption_Cipher(Key,String):
EncryptedMessage = ""
i = 0
j = 0
BinKey = Bin_It(Key)
BinString = Bin_It(String)
BinKeyLengh = len(BinKey)
BinStringLengh = len(BinString)
while ((BinKeyLengh > i) and (BinStringLengh > j)):
if((BinKey[i] == 'b')or(BinKey[i+1] == 'b')):
EncryptedMessage = EncryptedMessage + BinKey[i]
else:
EncryptedMessage = EncryptedMessage + Xor(BinKey[i],BinString[j])
i = i + 1
j = j + 1
if (i == BinKeyLengh):
i = i+j
return EncryptedMessage

这是 Bin_It 函数:

 def Bin_It(String):
TheBin = ""
for Charactere in String:
TheBin = TheBin + bin(ord(Charactere))
return TheBin

最后是 Xor 函数:

def Xor(a,b):
xor = (int(a) and not int(b)) or (not int(a) and int(b))
if xor:
return chr(1)
else:
return chr(0)

最佳答案

在您的 while 条件下,您确保 i < len(BinKey) .这意味着 BinKey[i]将有效,但 BinKey[i+1]在循环的最后一次迭代中将无效,因为您随后将访问 BinKey[len(BinKey)] ,这是你的字符串末尾的一个。 python 中的字符串从 0 开始结束于 len-1包容性。

为避免这种情况,您可以将循环标准更新为

while BinKeyLength > i+1 and ...:

关于python - python中的索引错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13330797/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com