Python转换字节为字符串可以使用decode函数,但decode函数在Python 2和Python3有所不同。
Python 2.7
help查看decode的函数说明
>>> help(b''.decode)
Help on built-in function decode:
decode(...)
S.decode([encoding[,errors]]) -> object
Decodes S using the codec registered for encoding. encoding defaults
to the default encoding. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
as well as any other name registered with codecs.register_error that is
able to handle UnicodeDecodeErrors.
Python 2.7的decode函数如果缺失encoding,使用的是系统默认的编码。
获取系统的默认编码
>>> import sys
>>> sys.getdefaultencoding()
'ascii'
这里的系统默认编码为ascii,如果是非‘ascii’使用decode函数不指定编码会抛出异常
>>> s=u'你好'
>>> b=s.encode('utf8')
>>> print b.decode()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal
not in range(128)
>>>
>>> print b.decode('utf8')
你好
字符串s使用utf8编码得到字节b,使用decode直接对字节b解码时,报ascii解码不了字节。使用decode指定解码为utf8后,解码正确。
所以,在Python 2使用decode对字节解码时,建议指定编码。
Python 3.x
使用help查看decode的帮助说明
>>> help(b''.decode)
Help on built-in function decode:
decode(encoding='utf-8', errors='strict') method of builtins.bytes instance
Decode the bytes using the codec registered for encoding.
encoding
The encoding with which to decode the bytes.
errors
The error handling scheme to use for the handling of decoding errors.
The default is 'strict' meaning that decoding errors raise a
UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
as well as any other name registered with codecs.register_error that
can handle UnicodeDecodeErrors.
可以看出Python3中decode函数的默认编码指定为了utf-8。所以
b'hello'.decode()
等同于
b'hello'.decode('utf-8')
>>> s='你好'
>>> b=s.encode('utf8')
>>> b.decode()
'你好'
在这个例子里,你会看到对字符串s的赋值,‘你好’是没有u作为前缀。这是因为系统的默认编码为utf8
查看系统编码
>>> import sys
>>> sys.getdefaultencoding()
'utf-8'
在python 3,系统的默认编码为utf-8