import base64 def safe_base64_decode(s): b = base64.b64encode(s.encode('utf-8'))#由於python3.x中字符都爲unicode編碼,而b64encode函數的參數爲byte類型,因此必須先轉碼 bstr_tmp = str(b,'utf-8') #把byte類型的數據轉換爲utf-8的數據 b_str= bstr_tmp.strip(r'=+') #用正則把 = 去掉 return b_str s = "binarybstr\x00string" safe_b = safe_base64_decode(s) print (safe_b)