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

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

好像我有一个索引问题,我不知道如何解决它。
错误信息是:
IndexError: string index out of range

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

所以我的问题是:
  • 如何解决问题,我做错了什么?
  • 看看我的代码,我可以学习什么来提高我的编程技能?
  • 我想为我的程序构建一个简单的界面(其中将包含所有加密密码),而我从谷歌想出的所有内容都是 pyqt,但对于一个非常简单的界面来说似乎工作太多了,所以有没有更简单的构建界面的方法? (我正在使用 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/

    10-11 22:30
    查看更多