Caesar Cipher problem in python

A Caesar cipher is a simple substitution cipher in which each letter of the plain text is substituted with a letter found by moving n places down the alphabet. For example, assume the input plain text is the following:

abcd xyz

If the shift value, n, is 4, then the encrypted text would be the following:

efgh bcd

You are to write a function that accepts two arguments, a plain-text message and a number of letters to shift in the cipher. The function will return an encrypted string with all letters transformed and all punctuation and whitespace remaining unchanged.

Okay, now that you’re ready, let’s look at this solution:

 1    # caesar.py
 2    import string
 3
 4    def caesar(plain_text, shift_num=1):
 5    letters = string.ascii_lowercase
 6    mask = letters[shift_num:] + letters[:shift_num]
 7    trantab = str.maketrans(letters, mask)
 8    return plain_text.translate(trantab)

Leave a Comment