50 XP

19. Caesar cipher

Intermediate strings loops

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, a to z and A to Z, shift places forward. Past z, wrap round to the start: with a shift of 3, x becomes a.
  • A negative shift moves letters backwards: with a shift of -1, a becomes z.
  • Capitals stay capitals, and lower-case letters stay lower case.
  • Every other character stays as it is: digits, spaces, punctuation, and letters outside a to z, 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

Inputtext = "abc", shift = 1
Output"bcd"
ExplanationEach letter moves one place forward.

Example 2

Inputtext = "Hello, World!", shift = 3
Output"Khoor, Zruog!"
ExplanationH becomes K; the comma, space and ! stay.

Example 3

Inputtext = "Zoë", shift = 2
Output"Bqë"
ExplanationZ wraps round to B; ë stays as it is.

Constraints

  • text has 0 to 100 characters, of any kind.
  • shift is a whole number from -26 to 26.

Submit also runs 10 more tests you can't see.

Practises Strings (lesson 4).

Code
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