Search code examples
python-2.7rot13

How to implement ROT13 on a string using python code to demonstrate string encryption?


I am trying to use the ROT 13 caeser cipher for a college encryption assignement in Python but I have no proper idea as to how it can be used. This is what I tried:

def rot13(s):
    Alphabets="ABCDEFGHIJKLMNOPQRSTUVWEXYZ"
    type (Alphabets)
    Rotate=Alphabets[13:]+ Alphabets[:13]
    Reus= lambda a: Rotate[Alphabets.find(a)]
    if Alphabets.find(a)>-1:
    else: s
    return ''.join(Reus(a) for a in s)
    rot13('rageofbahamut')

Is there any procedural guideline that can explain how to use this cipher? Any help is appreciated. Thank You.


Solution

  • This will encrypt using ROT13. Or any other rotation value you wish to use.

    alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    
    def encrypt(plain, rot):
        cipherText = ''
    
        for letter in plain:
            if letter in alphabet:
                cipherIndex = (alphabet.index(letter) + rot) % 26 # This handles the wrap around
                cipherText = cipherText + alphabet[cipherIndex]
            else:
                cipherText = cipherText + letter # Non alphabet characters are just appended.
        return cipherText
    
    plain = 'HELLO WORLD'
    rot = 13 # In case you want to change it
    print encrypt(plain,rot)