字符串索引超出范围(Python)

2024-06-25 07:12:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个程序来编码,解码和破解凯撒密码。在

我有一个函数,它将字符串中的字母按指定的量移动:

def shift(data, shifter):
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    data = list(data)
    counter = 0  #  we will use this to modify the list while we iterate over it
    for letter in data:
        letter = letter.lower()
        if letter not in alphabet:
            counter += 1
            continue
        lPos = alphabet.find(letter)
        if shifter >= 0:
            shiftedPos = lPos + (0 - shifter)
        else:
            shiftedPos = lPos + abs(shifter)
        if shiftedPos >= len(alphabet) - 1: shiftedPos -= len(alphabet)
        data[counter] = alphabet[shiftedPos]  #  update the letter
        counter += 1  # advance
    data = ''.join(data)  # make it into a string again
    return data

我有一个破解密码的函数:

^{pr2}$

但是,在选择“y”继续几次之后,我得到了以下IndexError

Traceback (most recent call last):
  File "CeaserCypher.py", line 152, in <module>
    crack()
  File "CeaserCypher.py", line 131, in crack
    negData = shift(data, 0 - shifter)
  File "CeaserCypher.py", line 60, in shift
    print(alphabet[shiftedPos])
IndexError: string index out of range

为什么我会遇到这个错误?我如何修复它?在


Tags: inpy密码dataifshiftlinecounter
1条回答
网友
1楼 · 发布于 2024-06-25 07:12:01

IndexError表示您尝试访问的索引不存在。在字符串中,这意味着您试图从字符串中的给定点获取字符。如果给定的点不存在,那么您将尝试获取一个不在字符串内部的字符。在

“0123456”[7]试图获取字符串中的第7个字符,但该索引不存在,因此引发了“IndexError”。在

字符串上的所有有效索引都小于字符串的长度(当使用len(string)时)。在您的例子中,alphabet[shiftedPos]引发IndexError,因为shiftedPos大于或等于字符串“alphabet”的长度。在

据我所知,当您这样越界时,您需要做的是在字符串上循环。”z“(字符25)通过说2而被定罪,并成为字符27。在本例中,您希望它现在变成字符2(字母“b”)。因此,应该使用模。将“alphabet[shiftedPos]”替换为“alphabet[shiftedPos%len(alphabet)]”,我相信这将解决这个问题。在

顺便说一句,模将一个数除以n,然后得到余数。实际上,它会减去n,直到这个数字小于n(所以它总是在您想要的范围内)。在

相关问题 更多 >