首页 > 解决方案 > 字节串解码的两种形式

问题描述

python3中以下两种转换有什么区别吗?

>>> b'hello'.decode()
'hello'
>>> b'hello'.decode('utf-8')
'hello'

就在今天,我遇到了第一种方法,这是我以前从未见过的(默认为 utf-8,还是没有明确设置和推断编码?

标签: python-3.x

解决方案


默认值确实是 'utf-8'

>>> help(b'hello'.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.

推荐阅读