Home / Python / Example programs / Strings

Python program: Caesar cipher

Encrypt and decrypt text by shifting each letter along the alphabet.

The code

def caesar(text, shift):
    result = ""
    for ch in text:
        if ch.isalpha():
            base = ord("A") if ch.isupper() else ord("a")
            result += chr((ord(ch) - base + shift) % 26 + base)
        else:
            result += ch
    return result

secret = caesar("Meet me at Southbank, 7pm!", 3)
print(secret)
print(caesar(secret, -3))

Output

Phhw ph dw Vrxwkedqn, 7sp!
Meet me at Southbank, 7pm!

How it works

ord turns a letter into a number and chr turns it back. % 26 wraps around, so Z shifted by 1 becomes A. Not secure, but a fun first cipher.

Python features used

Learn the ideas behind it in the free lesson Strings.