Letters are numbers
Use character codes to shift every letter along the alphabet. About 9 minutes.
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.
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.
out = []
for ch in s:
pos = ord(ch) - ord("a")
new = (pos + k) % 26
out.append(chr(new + ord("a")))
return "".join(out)- letter
- c
- shifted
- 2
- position
- 0
'a' is position 0. 0 + 2 = 2, which is 'c'.
What's x shifted forward by 4, wrapping round after z?
- Ab
- BA symbol past z
- Ct
Show the answer
b. x is position 23. 23 + 4 = 27, which wraps round to 1: b.
Shift every letter
Every character of s is a lowercase letter. Move each letter k places forward in the alphabet, wrapping from z back to a, and return the new string.
s = "abz", k = 2 → "cdb"
0 ≤ length of s ≤ 1,000 · 0 ≤ k ≤ 1,000