typestar

Caesar cipher in Python

The ancient substitution cipher, as a modular-arithmetic exercise.

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

How it works

  1. Shifts each letter by a fixed amount.
  2. % 26 wraps past z back around to a.
  3. Case is preserved; non-letters pass through untouched.

Keywords and builtins used here

The run, in numbers

Lines
9
Characters to type
207
Tokens
83
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 52 seconds.

Type this snippet

Step 9 of 9 in Strings, step 15 of 72 in Language basics.

← Previous Next →