The "jump the five" cypher

Question Q4.3.5

In the television series The Wire, drug dealers encrypt telephone numbers with a simple substitution cypher based on the standard layout of the phone keypad. Each digit of the number, with the exception of 5 and 0, is replaced with the corresponding digit on the other side of the 5 key ("jump the five''); 5 and 0 are exchanged. Thus, 555-867-5309 becomes 000-243-0751. Devise a one-line statement to encrypt and decrypt numbers encoded in this way.


Solution Q4.3.5

The following code encrypts (and decrypts) a telephone number held as a string using the "jump the 5'' method.

''.join(['5987604321'[int(i)] if i.isdigit() else '-' for i in '555-867-5309'])

The list comprehension loops over the characters in the phone number string and, for those characters which are digits, casts them into an int, i. i can then be used as an index into the string giving the encrypted digit.