python模块:base64

时间:2023-03-09 19:50:04
python模块:base64
base64模块是用来作base64编码解码的,在电子邮件中常见。
它可以把不能作为文本显示的二进制数据编码为可显示的文本信息,编码后文本大小增加1/3. 常用方法有:
b64encode & b64decode  #用来编解码字符串
urlsafe_b64encode & urlsafe_b64decode #用来对url进行base64编解码
例:
import base64

a = 'this is a test'
b = base64.b64encode(a.encode(encoding='utf-8'))
print(b)
print('----------------')
print(base64.b64decode(b)) x = 'http://www.baidu.com'
y = base64.urlsafe_b64encode(x.encode(encoding='utf-8'))
print(y)
print('*****************')
print(base64.urlsafe_b64decode(y))

输出结果为:

b'dGhpcyBpcyBhIHRlc3Q='
----------------
b'this is a test' b'aHR0cDovL3d3dy5iYWlkdS5jb20='
*****************
b'http://www.baidu.com'