20

我正在尝试编写两个程序,一个将字符串转换为base64,然后另一个将base64编码的字符串转换回字符串。
到目前为止,我无法通过 base64 编码部分,因为我不断收到错误

TypeError: expected bytes, not str

到目前为止,我的代码看起来像这样

def convertToBase64(stringToBeEncoded):
import base64
EncodedString= base64.b64encode(stringToBeEncoded)
return(EncodedString)
4

1 回答 1

48

字符串已经“解码”,因此 str 类没有“解码”功能。因此:

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

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

the_thing.decode(encoding)

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

the_string.encode(encoding)

就 base 64 的内容而言:使用 'base64' 作为上述编码的值会产生错误:

LookupError: unknown encoding: base64

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

import base64
help(base64)

你会看到base64有两个非常方便的函数,分别是b64decode和b64encode。b64 decode 返回一个字节数组,而 b64encode 需要一个字节数组。

要将字符串转换为其 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')
于 2012-11-07T10:29:29.400 回答