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 等编码之间的转换。
常见的编码转换分为以下几种情况:
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"
S.decode('utf8').encode('gb18030')好像不行。
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')
例如:a为unicode编码 要转为gb2312。a.encode('gb2312')
1 # -*- coding=gb2312 -*- 2 a = u"中文" 3 a_gb2312 = a.encode('gb2312') 4 print a_gb2312
例如: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
编码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)
保存到磁盘上时,需要把它转换为对应的编码,如utf-8和utf-16。
除上以上的编码方法,在读写文件时还可以使用codecs的open方法在读写时进行转换。