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