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