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

前端 未结 9 2026
一生所求
一生所求 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:39

    Since Python 3.5 this is finally no longer awkward:

    >>> b'\xde\xad\xbe\xef'.hex()
    'deadbeef'
    

    and reverse:

    >>> bytes.fromhex('deadbeef')
    b'\xde\xad\xbe\xef'
    

    works also with the mutable bytearray type.

    Reference: https://docs.python.org/3/library/stdtypes.html#bytes.hex

提交回复
热议问题