0

我正在尝试编写一个简单的 Rot13 编码器/解码器,它接受一个字符串并使用“编解码器”模块对其进行编码/解码。我正在尝试使用以下方法定义一个函数:codecs.encode('rot13_text', 'rot_13')

在函数之外使用编解码器模块没有问题。当我尝试使用codecs.encode(rot13_text, 'rot_13')定义函数时,我收到 NameError

到目前为止,我已经尝试了以下代码的许多变体:

import codecs

def rot13_encoder():
    rot13_text = input("Type the text to be encoded: ")
    codecs.encode(rot13_text, 'rot_13')
    print(rot13_text)

终端输出

>>> def rot13_encoder():
...     rot13_text = input("Type the text to encode and press enter: ")
...     codecs.encode(rot13_text, 'rot_13')
...     print(rot13_text)
...
>>> rot13_encoder()
Type the text to encode and press enter: HELLO
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in rot13_encoder
  File "<string>", line 1, in <module>
NameError: name 'HELLO' is not defined
>>>   
4

1 回答 1

1

看来您使用的是 python 2.7 或更早版本。

import codecs

def rot13_encoder(in_string):
    return codecs.encode(in_string, 'rot_13')

in_string = raw_input('Type the text to be encoded: ')
print(rot13_encoder(in_string))

在这种情况下,您应该使用raw_input(...)而不是input(...)

于 2019-09-09T08:24:15.523 回答