#first we need to import maketrans
>>> from string import maketrans
#now define the translation
#parameters are strings, not lists
#first parameter defines what will be found in the string
#second parameter defines what each will be changed to
>>> trans = maketrans('cdefg','abcde')
#define our string and translate
>>> s = 'deg'
>>> s.translate(trans)
'bce'
Now using maketrans and a few other suggestions from the comments, I have written a newly improved Caesar's Shift. Encode and decode use the same code, because a shift of 4 in one direction of a 26 character alphabet is equivalent to a shift of 22 in the other direction. I also used ascii_letters to shift my translation, which is 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'. The letter w may be encoded to be a A by a shift of 4, but the decoding will return the lowercase w. There was an error in my exception handling, which is now corrected.
No comments:
Post a Comment