How to implement the ROT13 algorithm (replace a letter with the 13th letter after it) in Python

1 Answer

0 votes
"""
ROT13 Cipher Implementation in Python.
"""

'''
ROT13 is a simple substitution cipher that replaces a letter with the 13th letter 
after it in the alphabet. Because the English alphabet has 26 letters (13 * 2), 
applying ROT13 twice restores the original text (it is its own inverse).
'''

import string

def rot13(text: str) -> str:
    """
    Transforms a string using the ROT13 substitution cipher.
    
    Args:
        text (str): The input string to transform.
        
    Returns:
        str: The transformed ROT13 string.
    """
    # Define lowercase and uppercase alphabets
    lower = string.ascii_lowercase
    upper = string.ascii_uppercase
    
    # Create a translation table that maps each letter 13 positions ahead, wrapping around
    trans_table = str.maketrans(
        lower + upper,
        lower[13:] + lower[:13] + upper[13:] + upper[:13]
    )
    
    # .translate() applies the character mapping efficiently in C under the hood
    return text.translate(trans_table)


def main() -> None:
    # Input string specified
    message = "Hello, World! 123"
    
    print(f"Original:  {message}")
    
    # Apply ROT13 encryption
    encrypted = rot13(message)
    print(f"ROT13:     {encrypted}")
    
    # ROT13 is its own inverse; applying it again decrypts the message
    decrypted = rot13(encrypted)
    print(f"Decrypted: {decrypted}")


if __name__ == "__main__":
    main()


'''
run:

Original:  Hello, World! 123
ROT13:     Uryyb, Jbeyq! 123
Decrypted: Hello, World! 123

'''

 



answered 3 days ago by avibootz
edited 2 days ago by avibootz

Related questions

...