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

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

    OK, the following answer is slightly beyond-scope if you only care about Python 3, but this question is the first Google hit even if you don't specify the Python version, so here's a way that works on both Python 2 and Python 3.

    I'm also interpreting the question to be about converting bytes to the str type: that is, bytes-y on Python 2, and Unicode-y on Python 3.

    Given that, the best approach I know is:

    import six
    
    bytes_to_hex_str = lambda b: ' '.join('%02x' % i for i in six.iterbytes(b))
    

    The following assertion will be true for either Python 2 or Python 3, assuming you haven't activated the unicode_literals future in Python 2:

    assert bytes_to_hex_str(b'jkl') == '6a 6b 6c'
    

    (Or you can use ''.join() to omit the space between the bytes, etc.)

提交回复
热议问题