Search code examples
pythoncaesar-cipher

How does `string.maketrans()` "decrypt" a message?


Could somebody please explain this code? I know it decrypts the message, but I'm interested to know exactly how the process is done.

import string

original = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc " \
    "dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq " \
    "rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu " \
    "ynnjw ml rfc spj."

table = string.maketrans(
    "abcdefghijklmnopqrstuvwxyz", "cdefghijklmnopqrstuvwxyzab"
)

print original.translate(table)

Solution

  • Changes a for c, b for d, c for e... etc, as defined by the two strings.

    abcdefghijklmnopqrstuvwxyz
    ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
    cdefghijklmnopqrstuvwxyzab
    

    In other words, it replaces a letter with the letter 2 letters after it :)

    See here http://www.tutorialspoint.com/python/string_maketrans.htm