字符串已经“解码”,因此str类没有“decode”函数。因此:
AttributeError: type object 'str' has no attribute 'decode'
如果您想将字节数组解码并转换为字符串,请调用以下方法:
the_thing.decode(encoding)
如果你想将字符串编码(转换成字节数组),请调用:
the_string.encode(encoding)
关于base64方面的问题:
在上述编码中使用“base64”作为值会导致错误:
LookupError: unknown encoding: base64
打开控制台并输入以下内容:
import base64
help(base64)
你会发现 base64 有两个非常方便的函数,即 b64decode 和 b64encode。b64decode 返回一个字节数组,而 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')
b = bytes(mystring, 'utf-8')
来实现,然后使用变量b
进行编码:EncodedString = base64.b64encode(b)
,这将返回一个bytearray。 - Andreas Wallner