##language:zh #pragma section-numbers off ##含有章节索引导航的 ZPyUG 文章通用模板 <> ## 默许导航,请保留 <> ##startInc = Python 编码转换 = {{{ k reply-to python-cn@googlegroups.com, to python-cn@googlegroups.com, date Sat, Mar 29, 2008 at 10:09 AM subject [CPyUG:45138] python 编码转换[zt] }}} 主要介绍了python的编码机制,unicode, utf-8, utf-16, GBK, GB2312,ISO-8859-1 等编码之间的转换。 '''常见的编码转换分为以下几种情况:''' == unicode 缺失转换 == {{{ Tim Wang reply-to python-cn@googlegroups.com to python-cn@googlegroups.com date Thu, Aug 21, 2008 at 21:02 subject [CPyUG:63028] 有问题请教 }}} `S="\u5317\u4eac"` * 如何把它转换成gb18030的北京? * `S.decode('utf8').encode('gb18030')`好像不行。 === 聲明成 unicode 后进行 === {{{ Jimmy Kuu reply-to python-cn@googlegroups.com to python-cn@googlegroups.com date Thu, Aug 21, 2008 at 21:18 }}} {{{#!python s = "\u5317\u4eac" s = eval("u'%s'" % s) s.encode('gb18030') }}} == unicode 转换为其它编码(GBK, GB2312等) == 例如:a为unicode编码 要转为gb2312。a.encode('gb2312') {{{#!python # -*- coding=gb2312 -*- a = u"中文" a_gb2312 = a.encode('gb2312') print a_gb2312 }}} == 其它编码(utf-8,GBK)转换为unicode == 例如:a为gb2312编码,要转为unicode. unicode(a, 'gb2312')或a.decode('gb2312') {{{#!python # -*- coding=gb2312 -*- a = u"中文" a_gb2312 = a.encode('gb2312') print a_gb2312 a_unicode = a_gb2312.decode('gb2312') assert(a_unicode == a) a_utf_8 = a_unicode.encode('utf-8') print a_utf_8 }}} == 非unicode编码之间的转换 == 编码1(GBK,GB2312) 转换为 编码2(utf-8,utf-16,ISO-8859-1) 可以先转为unicode再转为编码2 如gb2312转utf-8 {{{#!python # -*- coding=gb2312 -*- a = u"中文" a_gb2312 = a.encode('gb2312') print a_gb2312 a_unicode = a_gb2312.decode('gb2312') assert(a_unicode == a) a_utf_8 = a_unicode.encode('utf-8') print a_utf_8 }}} == 判断字符串的编码 == isinstance(s, str) 用来判断是否为一般字符串 isinstance(s, unicode) 用来判断是否为unicode 如果一个字符串已经是unicode了,再执行unicode转换有时会出错(并不都出错) 下面代码为将任意字符串转换为unicode {{{#!python def u(s, encoding): if isinstance(s, unicode): return s else: return unicode(s, encoding) }}} == unicode 与其它编码之间的区别 == * 为什么不所有的文件都使用unicode,还要用GBK,utf-8等编码呢? * unicode可以称为抽象编码,也就是它只是一种内部表示,一般不能直接保存。 保存到磁盘上时,需要把它转换为对应的编码,如utf-8和utf-16。 == 其它方法 == 除上以上的编码方法,在读写文件时还可以使用codecs的open方法在读写时进行转换。 ##endInc ---- '''反馈''' 创建 by -- ZoomQuiet [<>]