I created a simple program for performing a Caeser cipher on a user inputted string.
In order to allow the shift to go past the end of the list and back to the beginning, I simply duplicated all the list values for that list.
Is there a more pythonic way of achieving this result so that it will shift back to the beginning and continue to shift if the shift goes past the end of the list range?
while True:
x = input("Enter the message you would like to encrypt via a Caeser shift; or type 'exit': ")
if x == 'exit': break
y = int(input("Enter the number by which you would like to have the message Caeser shifted: "))
alphabet = list('abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz')
encoded = ''
for c in x:
if c.lower() in alphabet:
encoded += alphabet[alphabet.index(c)+y] if c.islower() else alphabet[alphabet.index(c.lower())+y].upper()
else:
encoded += c
print(encoded)
If you do want to do it this way, then you're best bet is to use modular arithmetic to calculate the index in
alphabet
:Some notes: you don't need to convert your alphabet to a list: strings are iterable too; a dictionary might be a better alternative data structure.