python2的代码怎么在3中跑,如何在Python 3.2或更高版本中使用'十六进制'编码?

In Python 2, to get a string representation of the hexadecimal digits in a string, you could do

>>> '\x12\x34\x56\x78'.encode('hex')

'12345678'

In Python 3, that doesn't work anymore (tested on Python 3.2 and 3.3):

>>> '\x12\x34\x56\x78'.encode('hex')

Traceback (most recent call last):

File "", line 1, in

LookupError: unknown encoding: hex

There is at least one answer here on SO that mentions that the hex codec has been removed in Python 3. But then, according to the docs, it was reintroduced in Python 3.2, as a "bytes-to-bytes mapping".

However, I don't know how to get these "bytes-to-bytes mappings" to work:

>>> b'\x12'.encode('hex')

Traceback (most recent call last):

File "", line 1, in

AttributeError: 'bytes' object has no attribute 'encode'

And the docs don't mention that either (at least not where I looked). I must be missing something simple, but I can't see what it is.

解决方案

You need to go via the codecs module and the hex_codec codec (or its hex alias if available*):

codecs.encode(b'\x12', 'hex_codec')

* From the documentation: "Changed in version 3.4: Restoration of the aliases for the binary transforms".

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值