What's the correct way to convert bytes to a hex string in Python 3?

前端 未结 9 2090
一生所求
一生所求 2020-11-22 14:11

What\'s the correct way to convert bytes to a hex string in Python 3?

I see claims of a bytes.hex method, bytes.decode codecs, and have tri

9条回答
  •  情书的邮戳
    2020-11-22 14:44

    Python has bytes-to-bytes standard codecs that perform convenient transformations like quoted-printable (fits into 7bits ascii), base64 (fits into alphanumerics), hex escaping, gzip and bz2 compression. In Python 2, you could do:

    b'foo'.encode('hex')
    

    In Python 3, str.encode / bytes.decode are strictly for bytes<->str conversions. Instead, you can do this, which works across Python 2 and Python 3 (s/encode/decode/g for the inverse):

    import codecs
    codecs.getencoder('hex')(b'foo')[0]
    

    Starting with Python 3.4, there is a less awkward option:

    codecs.encode(b'foo', 'hex')
    

    These misc codecs are also accessible inside their own modules (base64, zlib, bz2, uu, quopri, binascii); the API is less consistent, but for compression codecs it offers more control.

提交回复
热议问题