Design

Thursday, December 2, 2010

maketrans Python and Improved Caesar's Shift

Maketrans is used to translate strings, character for character. The characters can be symbols, letters, or numbers. The following short example is a Caesar's Shift moving backwards by two letters.
#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