Thursday, December 26, 2013

Python - ROT13 encode

"ROT13 ("rotate by 13 places", sometimes hyphenated ROT-13) is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet. ROT13 is an example of the Caesar cipher, developed in ancient Rome."


Here are 2 solutions to implement ROT13 in Python:

0. 1st solution:

import string

ROT13 = string.maketrans(\

def rot13_encode(user_text):
    return string.translate(user_text, ROT13)

This method works smoothly in the console but when using with the web it will raise error because of some special characters in the input:

  File "/usr/lib/python27/", line 498, in translate
    return s.translate(table + s[:0])
UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 128: ordinal not in range(128)

The Unicode version of translate requires a mapping from Unicode ordinals (which you can retrieve for a single character with ord) to Unicode ordinals. If you want to delete characters, you map to None:

 To fix that, use this function to translate those special characters before encoding:

def translate_non_alphanumerics(to_translate, translate_to=u'_'):
    not_letters_or_digits = u'!"#%\'()*+,-./:;<=>?@[\]^_`{|}~'
    translate_table = dict((ord(char), translate_to) for char in not_letters_or_digits)
    return to_translate.translate(translate_table)

1. 2nd solution, built-in string encode function:

def rot13_encode(user_text):
    return user_text.encode("rot13")

That's why I love Python! <3