形如下面的一段代码:
b64_encoded_bytes = base64.b64encode(zlib.compress(b'abcde'))
encoded_bytes_representation = str(b64_encoded_bytes) # this the cause
zlib.decompress(base64.b64decode(encoded_bytes_representation))
zlib.decopress时报错
zlib.error: Error -3 while decompressing: incorrect header check
原因在于str()方法的使用
python3文档中对str()方法的描述:
If neither encoding nor errors is given, str(object) returns object.str(), which is the “informal” or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a str() method, then str() falls back to returning repr(object).
str()方法的作用只是把
b'eJxLTEpOSQUABcgB8A=='
转换成了
"b'eJxLTEpOSQUABcgB8A=='"
而正确的转换应该是转换为
"eJxLTEpOSQUABcgB8A=="
解决方法是:
str()方法中指定编码方式
str(b64_encoded_bytes, 'utf-8')