一旦到达列表的末尾,就返回到开头,python

0 python caesar-cipher

我有一个包含所有字母的“字母表”列表,程序应该使用某个单词生成一个字母序列,使用给用户的数字,例如:

Word input = "sun"
Shift_number input = 3
alphabet = ['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']
Run Code Online (Sandbox Code Playgroud)

输出应该是“vxq”,因为索引向右移动了三个空格,我的问题是当索引的移动超过列表中的变量数量时,例如:

Word input = "zero"
Shift_number = 1
Run Code Online (Sandbox Code Playgroud)

输出应该是“afsp”,但我收到此错误:“列表索引超出范围”。我只需要索引从“z”到“a”

Jar*_*vis 5

取模以保持在数组边界内( ,返回大小为 26 的字母数组中的index % 26范围):0-25

>>> "".join([alphabet[(alphabet.index(i) + 3) % 26] for i in "sun"])
'vxq'
>>> "".join([alphabet[(alphabet.index(i) + 1) % 26] for i in "zero"])
'afsp'
Run Code Online (Sandbox Code Playgroud)

(alphabet.index(i) + N) % 26N将在数组中循环增加索引。