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
- Shifts each letter by a fixed amount.
% 26wraps past z back around to a.- Case is preserved; non-letters pass through untouched.
Keywords and builtins used here
caesarchrdefelseforifordreturn
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.
Step 9 of 9 in Strings, step 15 of 72 in Language basics.