pythoncaesar-cipher

Once the end of a list is reached go back to the beginning, python


I have the list "alphabet" that has all the letters, and the program should with a certain word generate a sequence of letters using an number that gives the user, eg:

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']

The output should be "vxq" because the index moved three spaces to the right, my problem is when the moves of the index exceeds the number of variables in the list, eg:

Word input = "zero"
Shift_number = 1

The output should be "afsp" but instead I get this error: "list index out of range". I just need that the index goes to "z" to "a"


Solution

  • Take modulus to stay within the array bounds (index % 26, returning a range between 0-25 in the alphabet array of size 26):

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

    (alphabet.index(i) + N) % 26 will increment the index by N cyclically in your array.