[Tutor] Python .decode issue

Peter Otten __peter__ at web.de
Tue Feb 11 13:49:02 CET 2014


eryksun wrote:

> On Tue, Feb 11, 2014 at 3:42 AM, Peter Otten <__peter__ at web.de> wrote:
>>
>> Unfortunately the bytes --> bytes conversion codecs in Python 2 have no
>> convenient analog in Python 3 yet.
>>
>> This will change in Python 3.4, where you can use
>>
>>>>> import codecs
>>>>> codecs.decode(b"ff10", "hex")
>> b'\xff\x10'
>>>>> codecs.encode(b"\xff\x10", "hex")
>> b'ff10'
> 
> 3.4 restores the "hex" alias to encodings.aliases.aliases. You can use
> "hex_codec" in earlier versions.
> 
>     >>> codecs.encode(b"\xff\x10", "hex_codec")
>     b'ff10'
>     >>> codecs.decode(b"ff10", "hex_codec")
>     b'\xff\x10'

Thanks for the correction.

>> But for now you are stuck with binascii.b2a_hex() etc.
> 
> The alternate names are binascii.hexlify and binascii.unhexlify.
> 
>     >>> binascii.hexlify(b'\xff\x10') # b2a_hex
>     b'ff10'
>     >>> binascii.unhexlify(b'ff10')   # a2b_hex
>     b'\xff\x10'




More information about the Tutor mailing list