Python 编码转换

k <[email protected]>
reply-to        [email protected],
to      [email protected],
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 <[email protected]>
reply-to        [email protected]
to      [email protected]
date    Thu, Aug 21, 2008 at 21:02
subject [CPyUG:63028] 有问题请教

S="\u5317\u4eac"

聲明成 unicode 后进行

Jimmy Kuu <[email protected]>
reply-to        [email protected]
to      [email protected]
date    Thu, Aug 21, 2008 at 21:18

   1 s = "\u5317\u4eac"
   2 s = eval("u'%s'" % s)
   3 s.encode('gb18030')

unicode 转换为其它编码(GBK, GB2312等)

例如:a为unicode编码 要转为gb2312。a.encode('gb2312')

   1 # -*- coding=gb2312 -*-
   2 a = u"中文"
   3 a_gb2312 = a.encode('gb2312')
   4 print a_gb2312

其它编码(utf-8,GBK)转换为unicode

例如:a为gb2312编码,要转为unicode. unicode(a, 'gb2312')或a.decode('gb2312')

   1 # -*- coding=gb2312 -*-
   2 a = u"中文"
   3 a_gb2312 = a.encode('gb2312')
   4 print a_gb2312
   5 
   6 a_unicode = a_gb2312.decode('gb2312')
   7 assert(a_unicode == a)
   8 a_utf_8 = a_unicode.encode('utf-8')
   9 print a_utf_8

非unicode编码之间的转换

编码1(GBK,GB2312) 转换为 编码2(utf-8,utf-16,ISO-8859-1)

可以先转为unicode再转为编码2

如gb2312转utf-8

   1 # -*- coding=gb2312 -*-
   2 a = u"中文"
   3 a_gb2312 = a.encode('gb2312')
   4 print a_gb2312
   5 
   6 a_unicode = a_gb2312.decode('gb2312')
   7 assert(a_unicode == a)
   8 a_utf_8 = a_unicode.encode('utf-8')
   9 print a_utf_8

判断字符串的编码

isinstance(s, str) 用来判断是否为一般字符串 isinstance(s, unicode) 用来判断是否为unicode 如果一个字符串已经是unicode了,再执行unicode转换有时会出错(并不都出错)

下面代码为将任意字符串转换为unicode

   1 def u(s, encoding):
   2    if isinstance(s, unicode):
   3        return s
   4    else:
   5        return unicode(s, encoding)

unicode 与其它编码之间的区别

保存到磁盘上时,需要把它转换为对应的编码,如utf-8和utf-16。

其它方法

除上以上的编码方法,在读写文件时还可以使用codecs的open方法在读写时进行转换。


反馈

创建 by -- ZoomQuiet [2008-03-29 03:22:30]

PyEnCode (last edited 2010-03-10 03:36:31 by ZoomQuiet)