python - Shifting within a list when past end range? -


i created simple program performing caeser cipher on user inputted string.

in order allow shift go past end of list , beginning, duplicated list values list.

is there more pythonic way of achieving result shift beginning , continue shift if shift goes past end of list range?

while true:     x = input("enter message encrypt via caeser shift; or type 'exit': ")     if x == 'exit': break     y = int(input("enter number have message caeser shifted: "))     alphabet = list('abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz')     encoded = ''     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 want way, you're best bet use modular arithmetic calculate index in alphabet:

while true:     x = input("enter message encrypt via caeser shift; or type 'exit': ")     if x == 'exit': break     y = int(input("enter number have message caeser shifted: "))     alphabet = 'abcdefghijklmnopqrstuvwxyz'     encoded = ''     c in x:         if c.lower() in alphabet:             = (alphabet.index(c.lower()) + y) % 26             encoded += alphabet[i] if c.islower() else alphabet[i].upper()         else:             encoded += c     print(encoded) 

some notes: don't need convert alphabet list: strings iterable too; dictionary might better alternative data structure.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -