Day 38 - String Encoder

New tool in the toolbox.

In section four of the Python Next Level course on Udemy , we begin working on a simple cryptographic example, where we attempt to solve a problem with an encrypted message. Apparently, the problem and solution dates back to the 1920’s, but it’s a fun problem to work through for an advanced level Python course. One of the first things that I learned was this:

#!/usr/bin/env python

import string

enc_table = string.maketrans('ABCDEF', '123456')
dec_table = string.maketrans('123456', 'ABCDEF')

enc = 'BED FACED'.translate(enc_table)

print enc

dec = enc.translate(dec_table)

print dec

There’s not a lot of meat here, but the point is to learn the maketrans method, and the translate method, which are both available from the string class in Python. With maketrans, you can see that we are taking two strings, and saying that the first character of the first string, is equal to the value of the first character in the second string- much like those secret decoder rings you’d get in a box of Cracker Jack (yes, I’m old enough to remember those). Once we’ve got our encoder and decoder tables, we can use them to translate a new string using those characters into an ‘encrypted’ message that uses the table as the value source.

This is ‘really’ simple, so I’m hoping that this builds up to something a bit more advanced. Either way, I’ll keep going….

Jason T Clark

Jason T Clark

Father. Musician. Gamer. Coder.

comments powered by Disqus
rss facebook twitter github youtube mail spotify instagram linkedin