Python encode()、decode()方法詳解


一、語法格式

  encode()

  簡介:以 encoding 指定的編碼格式編碼 string,如果出錯默認報一個 ValueError 的 異 常 , 除非 errors 指 定 的 是 'ignore' 或 者'replace'。

  語法格式:string.encode(encoding='**', errors='**')

  

  decode()

  簡介:以 encoding 指定的編碼格式解碼 string,如果出錯默認報一個 ValueError 的 異 常 , 除非 errors 指 定 的 是 'ignore' 或 者'replace'。

  語法格式:string.decode(encoding='**', errors='**')

 

其中,第二個參數errors是控制錯誤處理的策略:

默認的參數就是strict,代表遇到非法字符時拋出異常;
如果設置為ignore,則會忽略非法字符;
如果設置為replace,則會用?取代非法字符;
如果設置為xmlcharrefreplace,則使用XML的字符引用。

 

 

二、實例

#!/usr/bin/python
 str = "this is string example....wow!!!"; str = str.encode('base64','strict'); print "Encoded String: " + str; print "Decoded String: " + str.decode('base64','strict')

上例執行結果:

Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE= Decoded String: this is string example....wow!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM