How to ROT13 encode in Python3?

17.4k views Asked by At

The Python 3 documentation has rot13 listed on its codecs page.

I tried encoding a string using rot13 encoding:

import codecs
s  = "hello"
os = codecs.encode( s, "rot13" )
print(os)

This gives a unknown encoding: rot13 error. Is there a different way to use the in-built rot13 encoding? If this encoding has been removed in Python 3 (as Google search results seem to indicate), why is it still listed in Python3 documentation?

5

There are 5 answers

0
andrew cooke On BEST ANSWER

Aha! I thought it had been dropped from Python 3, but no - it is just that the interface has changed, because a codec has to return bytes (and this is str-to-str).

This is from http://www.wefearchange.org/2012/01/python-3-porting-fun-redux.html :

import codecs
s   = "hello"
enc = codecs.getencoder( "rot-13" )
os  = enc( s )[0]
0
wisbucky On

rot_13 was dropped in Python 3.0, then added back in v3.2. rot13 was added back in v3.4.

codecs.encode( s, "rot13" ) works perfectly fine in Python 3.4+

Actually, now you can use any punctuation character between rot and 13 now, including:

rot-13, rot@13, rot#13, etc.

https://docs.python.org/3/library/codecs.html#text-transforms

New in version 3.2: Restoration of the rot_13 text transform.
Changed in version 3.4: Restoration of the rot13 alias.

0
jfs On

In Python 3.2+, there is rot_13 str-to-str codec:

import codecs

print(codecs.encode("hello", "rot-13")) # -> uryyb
0
sysinfo On

First you need to install python library - https://pypi.org/project/endecrypt/

pip install endecrypt (windows)
pip3 install endecrypt (linux)

then,

from endecrypt import cipher

message_to_encode = "Hello World"
conversion = 'rot13conversion'

cipher.encode(message_to_encode, conversion )
# Uryyb Jbeyq

message_to_decode = "Uryyb Jbeyq"

cipher.decode(message_to_decode, conversion)
# Hello World
0
shalor1k On
def rot13(message):
    Rot13=''
    alphabit = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ'
    for i in message:
        if i in alphabit:
            Rot13 += alphabit[alphabit.index(i) + 13]
        else:
            Rot13 += i
    return Rot13
        

The code is very large , but I'm just learning