19. Caesar cipher
A Caesar cipher hides a message by moving every letter the same number of places along the alphabet. With a shift
of 3, a becomes d, b becomes e, and so on.
Write a function encode(text, shift) that takes a string text and a whole number shift, and returns the encoded
string:
- Move every English letter,
atozandAtoZ,shiftplaces forward. Pastz, wrap round to the start: with a shift of 3,xbecomesa. - A negative
shiftmoves letters backwards: with a shift of -1,abecomesz. - Capitals stay capitals, and lower-case letters stay lower case.
- Every other character stays as it is: digits, spaces, punctuation, and letters outside
atoz, such asé,ßorω. With a shift of 1,"café"becomes"dbgé".
A shift of 0 or 26 leaves every letter where it is, and an empty text gives an empty string "".
Example 1
text = "abc", shift = 1"bcd"Example 2
text = "Hello, World!", shift = 3"Khoor, Zruog!"Example 3
text = "Zoë", shift = 2"Bqë"Constraints
texthas 0 to 100 characters, of any kind.shiftis a whole number from -26 to 26.
Submit also runs 10 more tests you can't see.
Practises Strings (lesson 4).
- Letters have numbers:
ord("a")is 97,ord("z")is 122, andchr(97)is"a"again. Capitals run fromord("A"), 65, to 90. ord(ch) - ord("a")is a lower-case letter's place in the alphabet, 0 to 25. Add the shift and% 26wraps it round:(23 + 3) % 26is 0, soxbecomesa. It works for a negative shift too.- Move a character only when
"a" <= ch <= "z", or"A" <= ch <= "Z"(counting from"A"), and add every other character unchanged. Don't test withch.islower(): it is alsoTrueforéandß, which must stay as they are.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def encode(text, shift):
"""Encode text with a Caesar cipher.
text: str, the message
shift: int, how many places to move each letter a-z
and A-Z (a negative shift moves it back)
Returns: str, the message with those letters moved and
every other character as it was
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.