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'.