Search code examples
pythonstringpython-3.xhex

Python 3 string to hex


In Python 2 these all worked:

>>> "hello".encode("hex")
'68656c6c6f'
>>> b"hello".encode("hex")
'68656c6c6f'
>>> u"hello".encode("hex")
'68656c6c6f'

But in Python 3:

>>> "hello".encode("hex")
LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs

How to convert string to hex in Python 3?


Solution

  • The hex codec has been chucked in 3.x. Use binascii instead:

    >>> binascii.hexlify(b'hello')
    b'68656c6c6f'