Thursday, January 1, 2015

Maketrans and translate

Today I learned a really cool Python feature and I thought I would share it with you. It is especially of interest to those who like use Python for ciphers and things like that.

The trick uses two functions, string.maketrans and str.translate. Together you can make a substitution cipher(http://en.wikipedia.org/wiki/Substitution_cipher) in only 8 lines of Python! Take a look at this code


string.maketrans takes two strings and makes a translation table suitable for passing to str.translate that translates char 0 in the first string to char 0 in the second, and so on. str.translate takes a table from string.maketrans and translates the string object it is called as a method of according to the table. In the program given, the variable shift is the number to shift the letters by in the cipher and the variable text is the text to encode. A similar program could be written to decode.