Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

Letters are numbers underneath

Remember passing secret notes where every letter was shifted a few places along the alphabet? That's a Caesar cipher, and it's how this lesson works.

Inside the computer each character is stored as a number, and a to z sit in a row. So subtracting the code for "a" from a letter's code gives its position: a is 0, b is 1, z is 25. Adding the code for "a" back turns a position into a letter again.

Letter to position: subtract the code for a.
Position to letter: add the code for a back.

Wrap round after z

Shifting y forward by 3 should give b: after z, the alphabet starts again, like a clock going past 12. The remainder after dividing by 26 does the wrapping. Position 24 plus 3 is 27, and 27 wraps round to 1, which is b.

Forget the wrapping and letters near the end of the alphabet turn into symbols that aren't letters at all.

Forget to wrap: and letters fall off the end of the alphabet.
In code
out = []
for ch in s:
    pos = ord(ch) - ord("a")
    new = (pos + k) % 26
    out.append(chr(new + ord("a")))
return "".join(out)
s = "abz", k = 2
c
0
b
1
z
2
i
letter
c
shifted
2
position
0

'a' is position 0. 0 + 2 = 2, which is 'c'.

Move 1 of 4