encode和decode的妙用

为何会报错“UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)”?本文就来研究一下这个问题。html

字符串在Python内部的表示是unicode编码,所以,在作编码转换时,一般须要以unicode做为中间编码,即先将其余编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另外一种编码。 python

decode的做用是将其余编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码。 git

encode的做用是将unicode编码转换成其余编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码。 编程

所以,转码的时候必定要先搞明白,字符串str是什么编码,而后decode成unicode,而后再encode成其余编码网络

代码中字符串的默认编码与代码文件自己的编码一致。 ui

如:s='中文'编码

若是是在utf8的文件中,该字符串就是utf8编码,若是是在gb2312的文件中,则其编码为gb2312。这种状况下,要进行编码转换,都须要先用decode方法将其转换成unicode编码,再使用encode方法将其转换成其余编码。一般,在没有指定特定的编码方式时,都是使用的系统默认编码建立的代码文件。 spa

若是字符串是这样定义:s=u'中文'code

则该字符串的编码就被指定为unicode了,即python的内部编码,而与代码文件自己的编码无关。所以,对于这种状况作编码转换,只须要直接使用encode方法将其转换成指定编码便可。htm

若是一个字符串已是unicode了,再进行解码则将出错,所以一般要对其编码方式是否为unicode进行判断:

isinstance(s, unicode)  #用来判断是否为unicode 

用非unicode编码形式的str来encode会报错 

 如何得到系统的默认编码? 

#!/usr/bin/env python
#coding=utf-8
import sys
print sys.getdefaultencoding()  

该段程序在英文WindowsXP上输出为:ascii 

在某些IDE中,字符串的输出老是出现乱码,甚至错误,实际上是因为IDE的结果输出控制台自身不能显示字符串的编码,而不是程序自己的问题。 

如在UliPad中运行以下代码:

s=u"中文"
print s 

会提示:UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)。这是由于UliPad在英文WindowsXP上的控制台信息输出窗口是按照ascii编码输出的(英文系统的默认编码是ascii),而上面代码中的字符串是Unicode编码的,因此输出时产生了错误。

将最后一句改成:print s.encode('gb2312')

则能正确输出“中文”两个字。

若最后一句改成:print s.encode('utf8')

则输出:\xe4\xb8\xad\xe6\x96\x87,这是控制台信息输出窗口按照ascii编码输出utf8编码的字符串的结果。

unicode(str,'gb2312')与str.decode('gb2312')是同样的,都是将gb2312编码的str转为unicode编码 

使用str.__class__能够查看str的编码形式

原理说了半天,最后来个包治百病的吧:)

复制代码代码以下:


#!/usr/bin/env python 
#coding=utf-8 
s="中文" 

if isinstance(s, unicode): 
#s=u"中文" 
print s.encode('gb2312') 
else: 
#s="中文" 
print s.decode('utf-8').encode('gb2312')

作网络编程的时候,常常须要把接收到的数据用16进制的方式打印出来,方便查看。今天发如今Python下有这样一个简单的方法。

 

>>> "hello".encode("hex") 
'68656c6c6f'

 

相应的还能够

>>> '68656c6c6f'.decode("hex") 
'hello'

 

查了一下手册,还有这些codec可用

Codec

Aliases

Operand type

Purpose

base64_codec base64, base-64 byte string Convert operand to MIME base64
bz2_codec bz2 byte string Compress the operand using bz2
hex_codec hex byte string Convert operand to hexadecimal representation, with two digits per byte
idna
Unicode string Implements RFC 3490. New in version 2.3. See alsoencodings.idna
mbcs dbcs Unicode string Windows only: Encode operand according to the ANSI codepage (CP_ACP)
palmos
Unicode string Encoding of PalmOS 3.5
punycode
Unicode string Implements RFC 3492. New in version 2.3.
quopri_codec quopri, quoted-printable, quotedprintable byte string Convert operand to MIME quoted printable
raw_unicode_escape
Unicode string Produce a string that is suitable as raw Unicode literal in pythonsource code
rot_13 rot13 Unicode string Returns the Caesar-cypher encryption of the operand
string_escape
byte string Produce a string that is suitable as string literal in python source code
undefined
any Raise an exception for all conversions. Can be used as the system encoding if no automatic coercion between byte and Unicode strings is desired.
unicode_escape
Unicode string Produce a string that is suitable as Unicode literal in pythonsource code
unicode_internal
Unicode string Return the internal representation of the operand
uu_codec uu byte string Convert the operand using uuencode
zlib_codec zip, zlib byte string Compress the operand using gzip
相关文章
相关标签/搜索