I'm new to python, so the question may be stupid, but still,

hexOutput = main(hexLine) new.write(hexOutput.encode("hex")) 

These lines in version 2.7 worked without errors, but now it gives this:

'hex' is not a text encoding; use codecs.encode () to handle arbitrary codecs

How to fix the error?

  • Related question: Bytes - translation from line - jfs
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

Python 2.7:

 >>> b"abc".encode('hex') '616263' 

Python 3.5:

 >>> b"abc".hex() '616263' 

Python 2/3:

 >>> import binascii >>> binascii.hexlify(b'abc') '616263' 

Do not confuse binary data itself, for example, a sequence of bytes: 97, 98, 99 and their textual representation in the hexadecimal system of '616263' since 97 10 == 61 16, etc.

In Python 3:

 >>> b'a'[0] == 97 == 0x61 == 0b01100001 True 

If you want other Python 2 str.encode() conversions from str to str to support, you can use the codecs module in Python 2 or 3 — as recommended by the error message:

 >>> import codecs >>> codecs.encode('abc', 'rot13').encode() b'nop' >>> codecs.encode(_, 'zip') b'x\x9c\xcb\xcb/\x00\x00\x02\x9b\x01N' >>> codecs.encode(_, 'hex') b'789ccbcb2f0000029b014e' 

bytes.encode() removed in Python 3 to highlight the differences from str type (Unicode in Python 3) and eliminate errors associated with implicit conversion of bytes to Unicode text and back.