pythondecode函数_Python2与Python3字节转换为字符串函数decode的区别

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 "", line 1, in

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值