Caesar Cipher
Medium · 55 XPShift every lowercase letter in "hello world" forward by 3 (wrapping z→c), keep spaces, and print the result.
khoor zruog
chr((ord(ch) - ord('a') + shift) % 26 + ord('a')) for letters; keep spaces as-is.
message = "hello world"
shift = 3
result = ""
for ch in message:
if ch == " ":
result += ch
else:
result += chr((ord(ch) - ord("a") + shift) % 26 + ord("a"))
print(result)
Run your code to check it…
How to approach Caesar Cipher
Letters are characters, but shifting is arithmetic, so the trick is converting back and forth. ord(ch) turns a character into its number and chr(n) turns a number back into a character.
Subtracting ord("a") maps a to 0 through z to 25. Add the shift, take % 26 so that 26 wraps back to 0, then add ord("a") back. Spaces are not letters, so leave them exactly as they are.
Worked through on this data
- h is position 7. 7 + 3 = 10, which is k. The same move turns e into h and l into o, so "hello" becomes "khoor".
- w is position 22. 22 + 3 = 25, which is z. o becomes r, r becomes u, l becomes o, d becomes g: "zruog".
- The space passes through untouched, giving "khoor zruog". The wrap matters for letters near the end: z is 25, 25 + 3 = 28, and 28 % 26 = 2, which is c.
Common mistakes
- Skipping
% 26works on this message by luck, but shifts z to a curly brace}. - Shifting the space as if it were a letter corrupts the word boundary.
- Uppercase letters live at a different range (A is 65, a is 97). Handle them with their own base, or the output fills with symbols.
Time and space
One pass, constant work per character: O(n) time. Building a new string is O(n) space; collect characters in a list and "".join() them to avoid repeated string copies.
Where this shows up
Nobody protects data with a Caesar cipher today, but modular arithmetic on character codes is exactly how checksums, hash functions and ROT13 spoiler text work.
Take it further
Write decode(message, shift) and show that decoding the encoded text returns "hello world". Bonus: do both with str.maketrans and str.translate.