【问题标题】:How to ROT13 encode in Python3?如何在 Python3 中进行 ROT13 编码?
【发布时间】:2012-05-14 00:34:56
【问题描述】:

Python 3 文档在其codecs page 中列出了 rot13。

我尝试使用 rot13 编码对字符串进行编码:

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

这会产生unknown encoding: rot13 错误。有没有不同的方法来使用内置的 rot13 编码?如果在 Python 3 中删除了这种编码(如 Google 搜索结果所示),为什么它仍然在 Python3 文档中列出?

【问题讨论】:

  • 您尝试了s.encode("rot13") 还是s.encode("rot_13")?我认为没有codecs.encode 这样的东西,只有codecs.Codec().encode
  • agf:codecs.Codec().encode()函数只接受字符串输入,没有参数传入编码类型。
  • 你不应该影响os。 ಠ_ಠ

标签: python python-3.x rot13


【解决方案1】:

在 Python 3.2+ 中,有 rot_13 str-to-str codec:

import codecs

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

【讨论】:

    【解决方案2】:

    啊哈!我以为它已从 Python 3 中删除,但没有——只是接口发生了变化,因为编解码器必须返回字节(这是 str-to-str)。

    这是来自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]
    

    【讨论】:

      【解决方案3】:

      rot_13 在 Python 3.0 中被删除,然后在 v3.2 中重新添加。 rot13 在 v3.4 中重新添加。

      codecs.encode( s, "rot13" ) 在 Python 3.4+ 中运行良好

      其实,现在你可以使用rot13之间的任何标点符号,包括:

      rot-13rot@13rot#13

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

      3.2 版中的新功能:恢复 rot_13 文本转换。
      在 3.4 版更改: rot13 别名的恢复。

      【讨论】:

        【解决方案4】:
        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
                
        

        代码很大,只是学习

        【讨论】:

          【解决方案5】:

          首先你需要安装python库-https://pypi.org/project/endecrypt/

          pip install endecrypt (windows)
          pip3 安装加密 (linux)

          那么,

          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
          

          【讨论】:

            最近更新 更多