Python凯撒密码脚本出现IndexError: list index out of range错误求助
修复凯撒密码解密脚本的IndexError问题
我在解决picoCTF挑战时,需要解密凯撒密码加密的flag:cvpbPGS{c33xno00_1_f33_h_qrnqorrs},编写了如下Python脚本,但运行时触发了IndexError: list index out of range错误:
原脚本
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
问题分析
- 索引越界根源:列表的合法索引范围是
0到len(列表)-1,你的while循环条件是this > len(alpha_lower),当this等于列表长度时(比如字母z的索引25加1得到26,而列表长度正好是26),条件不触发,直接调用alpha_lower[26]就会越界,应该把条件改成this >= len(alpha_lower)。 - 非字母字符丢失:脚本未处理数字、下划线、大括号这类非字母字符,这些字符会被直接跳过,导致输出文本缺失关键格式和内容。
修复后的脚本
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 = 'cvpbPGS{c33xno00_1_f33_h_qrnqorrs}' for shift in range(len(alpha_lower)): temp = '' for char in text: if char.islower(): ind = alpha_lower.index(char) new_ind = (ind + shift) % len(alpha_lower) # 用取模替代while循环,简洁高效 temp += alpha_lower[new_ind] elif char.isupper(): ind = alpha_upper.index(char) new_ind = (ind + shift) % len(alpha_upper) temp += alpha_upper[new_ind] else: # 非字母字符直接保留,保证格式完整 temp += char print(f"位移{shift}: {temp}")
优化说明
- 用取模运算替代while循环,自动处理循环位移逻辑,避免手动减长度的繁琐操作。
- 给循环变量改名(
iterator→shift),让代码语义更直观。 - 保留了原flag中的大括号,确保输出格式符合picoCTF的要求。
运行修复后的脚本,就能找到正确的解密结果(凯撒密码常见位移为13,对应输出即为明文flag)。
内容的提问来源于stack exchange,提问作者Mani
相关产品推荐
相关产品推荐

