【发布时间】:2023-02-08 00:57:27
【问题描述】:
我创建了一个包含 26 个项目的列表。
字母表 = ['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']
我希望使用将字母移动到下一个选定位置:即“hello”移动位置 5 并将文本返回为“mjqqt”
为此,我使用了“for 循环”,它也能正常工作,直到我使用字母 z,因为它是列表中的最后一项。
有没有一种方法可以在到达字母表 [25] 后循环列表以重新启动到字母表 [0] 的位置,这意味着当换档字母为“z”并按位置 5 移动时,我希望它从位置 0 重新开始返回“e”
我创建了一个函数,用于循环移动单词中的每个字母并返回加密的 cipher_text。
def encrypt(plain_text, shift_amount):
cipher_text = ""
for letter in plain_text:
position = alphabet.index(letter)
new_position = position + shift_amount
cipher_text += alphabet[new_position]
print(f"The encoded text is {cipher_text}")
encrypt(plain_text=text, shift_amount=shift)
错误: 追溯(最近一次通话): 文件“\caesar-cipher\caesar-cipher-4 Final.py”,第 36 行,位于 加密(纯文本=文本,shift_amount=shift)
IndexError:列表索引超出范围
【问题讨论】:
-
所以如果字母是 z (25) 并且移位是 5,那就是 IndexError
-
正确的。这就是为什么我需要知道我们是否可以通过将 alphabet[25] + shift 移动 5(即 alphabet[30])来使其工作,就像将它移动到列表的第 4 位而不是寻找第 30 位的项目一样
标签: python-3.x list loops index-error