首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用"codecs“模块定义函数时遇到麻烦

使用"codecs“模块定义函数时遇到麻烦
EN

Stack Overflow用户
提问于 2019-09-09 08:16:06
回答 1查看 37关注 0票数 0

我试图编写一个简单的Rot13编码器/解码器,它接受一个字符串,并使用“编解码”模块对其进行编码/解码。我试图使用:codecs.encode(‘rot13 13_text’,'rot_13')定义一个函数

我没有问题使用编解码模块以外的一个函数。当我试图使用codecs.encode(rot13_text,'rot_13')定义一个函数时,我会收到一个NameError

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

代码语言:javascript
复制
import codecs

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

终端输出

代码语言:javascript
复制
>>> 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
>>>   
EN

回答 1

Stack Overflow用户

发布于 2019-09-09 08:24:15

您似乎正在使用python2.7或更早版本。

代码语言:javascript
复制
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(...)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57850158

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档