Possible Duplicate:
Converting a string to and from Base 64

def convertFromBase64 (stringToBeDecoded):
    import base64
    decodedstring=str.decode('base64',"stringToBeDecoded")
    print(decodedstring)
    return

convertFromBase64(dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=)

我打算把一个base64编码的字符串转换回原始字符串,但我不知道到底出了什么问题

我犯了这个错误

 Traceback (most recent call last):
 File "C:/Python32/junk", line 6, in <module>
convertFromBase64(("dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE="))
 File "C:/Python32/junk", line 3, in convertFromBase64
decodedstring=str.decode('base64',"stringToBeDecoded")
AttributeError: type object 'str' has no attribute 'decode'

推荐答案

字符串已经"解码",因此str类没有"解码"函数.因此:

AttributeError: type object 'str' has no attribute 'decode'

如果要解码字节数组并将其转换为字符串调用:

the_thing.decode(encoding)

如果要对字符串进行编码(将其转换为字节数组),请调用:

the_string.encode(encoding)

就基本64个方面而言:

LookupError: unknown encoding: base64

打开控制台并键入以下内容:

import base64
help(base64)

您将看到base64有两个非常方便的功能,即B64解码和B64编码.b64解码返回字节数组,b64编码需要字节array.

要将字符串转换为base64表示形式,首先需要将其转换为字节.我喜欢utf-8,但是使用你需要的任何编码...

import base64
def stringToBase64(s):
    return base64.b64encode(s.encode('utf-8'))

def base64ToString(b):
    return base64.b64decode(b).decode('utf-8')

Python-3.x相关问答推荐

使用 Fetch 提交表单到 Django 视图

如何将值映射到具有上限和下限的新列

为什么不能用格式字符串 '-' 绘制点?

无法理解此递归函数的分配和环境用法

使用 Python 在特定组的列中设置上限

使用正则表达式提取字符串之间的文本

如何准确测定cv2的结果.在BW/黑白图像中查找对象?

请求:RecursionError:超出最大递归深度

Python - 使用 OpenCV 将字节图像转换为 NumPy 数组

从 Python2 到 Python3 的这种解包行为的变化是什么?

将变量传递给 Google Cloud 函数

如何从另一个目录导入 python 包?

numpy.ndarray 与 pandas.DataFrame

Python 解包运算符 (*)

python asyncio - 如何等待取消的屏蔽任务?

定义 True,如果没有定义,会导致语法错误

如何在 jupyter notebook 5 中逐行分析 python 3.5 代码

当默认 pip 为 pip2 时,升级 pip3 的正确格式是什么?

命名参数可以与 Python 枚举一起使用吗?

同步调用协程