Chapter 3: Object methods

Caesar cipher

face Josiah Wang Oana Cocarascu

Was that fun? Let’s do another challenge!

Write a function apply_cipher() that applies Caesar cipher to any given string.

Caesar cipher is a method of encrypting a piece of text by replacing each letter in the text with a letter that is N steps further down the alphabet.

For example, if we set the shift to be “3 to the left”, then D will be replaced with A, E will be replaced with B. We also assume that the shift is ‘cyclic’, so A will be replaced with X, B will be replaced with Y, and C will be replaced with Z.

Caesar cipher left shift of 3

Remember that the English alphabet has 26 letters.

The function apply_cipher() should take two inputs: an input str, and an int representing by how much the character should be shifted. A positive shift will shift the characters to the right, and a negative shift will shift the characters to the left. Set the shift to 0 by default.

For example, given the input string "THE quick Brown fox JuMpS Over the lazy dog" and a shift value of -3, the function should return "QEB nrfzh Yoltk clu GrJmP Lsbo qeb ixwv ald".

You can assume that the input string will consist of only uppercase letters, lowercase letters and spaces.

You might find Python’s string module useful for accessing a string of lowercase or uppercase letters.

>>> import string
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'

Sample usage

>>> apply_cipher("Python Programming", 10)
Zidryx Zbyqbkwwsxq
>>> apply_cipher("THE quick Brown fox JuMpS Over the lazy dog", -3)
QEB nrfzh Yoltk clu GrJmP Lsbo qeb ixwv ald
>>> apply_cipher("THE quick Brown fox JuMpS Over the lazy dog")
THE quick Brown fox JuMpS Over the lazy dog