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!!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章