P4.3.2The ROT-13 cypher
The ROT13 substitution cipher encodes a string by replacing each letter with the letter 13 letters after it in the alphabet (cycling around if necessary). For example, a \(\rightarrow\) n and p \(\rightarrow\) c.
(a) Given a word expressed as a string of lower-case characters only, use a list comprehension to construct the ROT13-encoded version of that string. Hints: Python has a built-in function, ord, which converts a character to its Unicode code point (e.g. ord('a') returns 97); another builtin, chr is the inverse of ord (e.g. chr(122) returns 'z').
(b) Extend your list comprehension to encode sentences of words (in lower-case) separated by spaces into a ROT13 sentence (in which the encoded words are also separated by spaces).
Show solution
(a) This type of thing is usually frowned-upon in Python circles:
''.join([chr((ord(c) - 84) % 26 + 97) for c in s])
(b) This could be achieved with two list comprehensions as follows:
' '.join([''.join([chr((ord(c) - 84) % 26 + 97) for c in w]) for w in s.split()])