16

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?

pppery
  • 3,731
  • 22
  • 33
  • 46
Ashwin Nanjappa
  • 76,204
  • 83
  • 211
  • 292
  • 1
    Did you try just `s.encode("rot13")` or `s.encode("rot_13")`? I don't think there is any such thing as `codecs.encode`, just `codecs.Codec().encode` – agf May 14 '12 at 00:37
  • agf: The codecs.Codec().encode() function only takes in string input, there is no parameter to pass in the encoding type. – Ashwin Nanjappa May 14 '12 at 01:14
  • 4
    You shouldn't shadow `os`. ಠ_ಠ – alexia Feb 26 '14 at 13:47

5 Answers5

24

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

import codecs

print(codecs.encode("hello", "rot-13")) # -> uryyb
jfs
  • 399,953
  • 195
  • 994
  • 1,670
10

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]
Ashwin Nanjappa
  • 76,204
  • 83
  • 211
  • 292
andrew cooke
  • 45,717
  • 10
  • 93
  • 143
1

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.

wisbucky
  • 33,218
  • 10
  • 150
  • 101
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

David Buck
  • 3,752
  • 35
  • 31
  • 35
shalor1k
  • 101
  • 4
0

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
sysinfo
  • 49
  • 4