python使用base64编码

base64原理

base64编码

将字符串、文件 编码成 base64格式

因为3.x中字符都为unicode编码,而b64encode函数的参数为byte类型,所以必须先转码

import base64
s = '测试base64'

#先讲string转换为bytes
byteS=s.encode(encoding="utf-8")

#打印结果为b'\xe6\xb5\x8b\xe8\xaf\x95base64',此处有b,说明是bytes型
print(byteS)

#进行base64编码,返回也是bytes
byteBase64 = base64.b64encode(byteS)

#打印结果为b'5rWL6K+VYmFzZTY0',此处有b,说明是bytes型
print(byteBase64)

#将bytes转换为字符串
stringBase64=byteBase64.decode()
print(stringBase64)

base64解码

将base64格式 解码成 字符串、文件

# 解码后,是bytes类型
data=base64.b64decode(byteBase64)

# 将bytes类型 转成 字符串
s=data.decode(encoding="utf-8")
print(s)

原文出处:/show_1EF1GNN8r1oT.html