请写一个能处理去掉=
的base64解码函数:
import base64
def safe_base64_decode(s):
# print(type(s))
while True:
if len(s)%4 !=0:
s=s+b"="
else: break
return base64.b64decode(s)
# 测试:
print(safe_base64_decode(b'YWJjZA=='))
print(safe_base64_decode(b'YWJjZA'))
assert b'abcd' == safe_base64_decode(b'YWJjZA=='), safe_base64_decode('YWJjZA==')
assert b'abcd' == safe_base64_decode(b'YWJjZA'), safe_base64_decode('YWJjZA')
print('ok')
Python内置的base64
可以直接进行base64的编解码:
>>> import base64
>>> base64.b64encode(b'binary\x00string')
b'YmluYXJ5AHN0cmluZw=='
>>> base64.b64decode(b'YmluYXJ5AHN0cmluZw==')
b'binary\x00string'
Base64的原理很简单,首先,准备一个包含64个字符的数组:
['A', 'B', 'C', ... 'a', 'b', 'c', ... '0', '1', ... '+', '/']
然后,对二进制数据进行处理,每3个字节一组,一共是3x8=24
bit,划为4组,每组正好6个bit:
这样我们得到4个数字作为索引,然后查表,获得相应的4个字符,就是编码后的字符串。
所以,Base64编码会把3字节的二进制数据编码为4字节的文本数据,长度增加33%,好处是编码后的文本数据可以在邮件正文、网页等直接显示。
python 3 assert
格式:assert+空格+要判断语句+双引号“报错语句”