简体   繁体   中英

How to ROT13 encode in Python3?

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?

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

import codecs

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

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]
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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM