python-3.x 错误,索引超出范围,发生了什么错误?

eblbsuwk  于 2023-02-06  发布在  Python
关注(0)|答案(2)|浏览(89)

我编写了一个Python3脚本来解决picoCTF挑战。我收到了加密标志,它是:cvpbPGS{c33xno00_1_f33_h_qrnqorrs}从它的模式来看,我以为它是用凯撒密码编码的,所以我写了这个脚本:

alpha_lower = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
        'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u','v', 'w', 'x', 'y', 'z']
alpha_upper = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
        'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
text = 'cvpbPGSc33xno00_1_f33_h_qrnqorrs '

for iterator in range(len(alpha_lower)):
    temp = ''
    for char in text:
        if char.islower():
        
            ind = alpha_lower.index(char)
            this = ind + iterator
            
            while this > len(alpha_lower):
                this -= len(alpha_lower)
                
            temp += alpha_lower[this]
            
        elif char.isupper():
            ind = alpha_upper.index(char)
            that = ind + iterator
            
            while that > len(alpha_upper):
                that -= len(alpha_upper)

            temp += alpha_upper[that]
    print(temp)

我知道错误的意思。我不知道缺陷在哪里。提前感谢。
错误提示:

Desktop>python this.py 
cvpbPGScxnofhqrnqorrs  
dwqcQHTdyopgirsorpsst
exrdRIUezpqhjstpsqttu
Traceback (most recent call last):
File "C:\Users\user\Desktop\this.py", line 18, in <module>
temp += alpha_lower[this]
IndexError: list index out of range
nhaq1z21

nhaq1z211#

为什么这种突破很简单:如果this==len(alpha_lower),则我们不会进入您的循环:while this > len(alpha_lower):因此当尝试temp += alpha_lower[this]时,它将返回一个错误。索引必须严格小于数组的大小。您的条件应该是while this >= len(alpha_lower):。正如所指出的,这里更好的方法是使用模数。

o8x7eapl

o8x7eapl2#

  • 您的方法存在错误,因为ind + iterator的最大可能值为50,大于len(alpha_lower)
  • 要修复此问题,可以使用取模运算符:(ind + iterator) % len(alpha_lower)
  • 有一种不太复杂的方法来解码Caesar密码,您应该使用ord()chr()函数来manipulate unicode值,而不是使用两个不同的大小写字符列表。

相关问题