歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python base64解碼TypeError: Incorrect padding錯誤處理

Python base64解碼TypeError: Incorrect padding錯誤處理

日期:2017/3/1 9:43:12   编辑:Linux編程

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字符串

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved