字符串已经“解码”,因此 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')