ROT13 is a very simple cipher. Among other things, it has long been used on USENET to make some text slightly more difficult to read.

Two new functions are going to help us implement ROT13 in Python. These are chr and ord. To understand these two functions a basic understanding of ASCII is necessary. ASCII is the character encoding used for basic English text. At a low level on the computer, each character of a string is represented by an 8-bit number with the mapping defined by ASCII. Take a look at man ascii for details.

The chr and ord functions can be used to translate back and forth between a character representation and the ASCII code.

print ord('a')      # Prints 97
print chr(97)       # Prints a
x = ord('b')        # Stores 98 into x
x += 1              # Update x to 99
print chr(x)        # Prints c

Note that in ASCII we can rotate some letters by directly adding 13 to the ASCII code. For example:

  • The ASCII code for a is 97

  • 97 + 13 = 110

  • The ASCII code 110 maps to n

  • The letter n is ROT13 of a

However, for other letters this does not work.

  • The ASCII code for n is 110

  • 110 + 13 = 123

  • The ASCII code 123 maps to {

  • The character { is not ROT13 of n (at least not in the Caesar cipher sense)

With this knowledge in hand we can begin implementing ROT13.

Challenges to Work Through

  • Write a function that takes as input a list of integers and returns the string built using those integers as ASCII codes. Call the function from_ascii.

  • Write a function that takes as input a string and returns an array containing the ASCII codes of the characters in the string. Call the function to_ascii.

  • Write a function that takes as input a list of integers and returns a new list of integers made by incrementing each element of the original list by 2.

  • Write a function called rot13 that takes as input a single lower case letter and returns the ROT13 of that letter. Note that the return value should always be a letter.

  • Extend the function rot13 to handle upper case letters. In particular, rot13(a) should return the character n and `rot13(A) should return the character N.

  • Extend the function rot13 (again!) to handle non-alphabetic characters. Any non-alphabetic character should be returned unchanged.

  • Write a functions that takes as input a string and returns the ROT13 of that string.