Python字符串的编码和解码(转)

2013-05-01  文晶 
Python字符串的编码和解码

2007-01-10 13:16:22| 分类: Python | 标签: |字号 订阅

#coding: gbk
unicodestring = u"Hello, 中国"
#Convent Unicode to plain Python string: "encode"
utf8string = unicodestring.encode("utf-8")
utf16string = unicodestring.encode("utf-16")
gbkstring = unicodestring.encode("gbk")
cp932string = unicodestring.encode("cp932")
#Convent plain Python string to Unicode: "decode"
unicodestring1 = unicode(utf8string, "utf-8")
unicodestring2 = unicode(utf16string, "utf-16")
unicodestring3 = unicode(gbkstring, "gbk")
unicodestring4 = unicode(cp932string, "cp932")
概括的说,调用一个unicode对象的encode方法,返回相应编码的string对象;调用某种编码的string对象的decode或调用unicode方法,返回一个unicode对象
249°|2498 人阅读|0 条评论
登录 后发表评论