Python base64解码TypeError: Incorrect padding错误处理

2014-11-23 22:59:17 · 作者: · 浏览: 14

Python 自带的base64库,在解码base64字符串的时候抛异常 TypeError: Incorrect padding。

代码如下:


>>> b='5paw5Lqn5ZOB55qE5biC5Zy6566h55CGMWk'
>>> base64.b64decode(b)
Traceback (most recent call last):
File "", line 1, in
File "D:\Python27\Lib\base64.py", line 76, in b64decode
raise TypeError(msg)
TypeError: Incorrect padding


http://stackoverflow.com/questions/2941995/python-ignore-incorrect-padding-error-when-base64-decoding找到解决办法。原理没有看明白,先用着再说。


解决办法如下


lens = len(strg)
lenx = lens - (lens % 4 if lens % 4 else 4)
try:
result = base64.decodestring(strg[:lenx])
except:
pass


其中strg是需要解码的base64字符串