Caesar Cipher Function in Python

I realize that this answer doesn’t really answer your question, but I think it’s helpful anyway. Here’s an alternative way to implementing the caesar cipher with string methods:

def caesar(plaintext, shift):
    alphabet = string.ascii_lowercase
    shifted_alphabet = alphabet[shift:] + alphabet[:shift]
    table = string.maketrans(alphabet, shifted_alphabet)
    return plaintext.translate(table)

In fact, since string methods are implemented in C, we will see an increase in performance with this version. This is what I would consider the ‘pythonic’ way of doing this.

Leave a Comment