这篇博客是从旧博客 WordPress 迁移过来,内容可能存在转换异常。
字符串在Python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。
decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码。
encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码。
获得当前系统的编码:
import sys
sys.getdefaultencoding()
也可以修改编码方式:
encoding=GBK
import sys
reload(sys)
sys.setdefaultencoding('gbk')
参考:
http://hi.baidu.com/tornadory/blog/item/2fa5f0c36cf7bd5fb219a801.html
http://blog.csdn.net/wumeng0204/article/details/6606712
http://www.iteye.com/topic/66558
http://boodebr.org/main/python/all-about-python-and-unicode#STARTINGPOINT
http://www.joelonsoftware.com/articles/Unicode.html