如何在Python 3.2或更高版本中使用'十六进制'编码? [英] How to use the 'hex' encoding in Python 3.2 or higher?

查看:553
本文介绍了如何在Python 3.2或更高版本中使用'十六进制'编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 2中,为了获得字符串中十六进制数字的字符串表示,您可以执行

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

在Python 3中,这不再适用(在Python 3.2和3.3中测试):

  >>> '\x12\x34\x56\x78'.encode('hex')
Traceback(最近一次调用的最后一个):
文件< stdin>,line 1,in< ;模块>
LookupError:unknown encoding:hex

至少一个答案,这里提到在Python 3中已经删除了 hex codec。但是,根据文档 ,它在Python 3.2中重新引入,作为字节到字节的映射。



然而,我不知道如何让这些字节到字节的映射工作:

 >>> b'\x12'.encode('hex')
Traceback(最近一次调用的最后一个):
在< module>中,第1行的文件< stdin>
AttributeError:'bytes'对象没有属性'encode'

不要说(至少不是我看过的地方)。我必须缺少一些简单的东西,但我看不到它是什么。

解决方案

您需要通过 codecs 模块和 hex_codec 编解码器(或其 hex 别名(如果可用):

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

*从文档:在版本3.4中进行了更改:恢复二进制转换的别名


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 "<stdin>", line 1, in <module>
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 "<stdin>", line 1, in <module>
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".

这篇关于如何在Python 3.2或更高版本中使用'十六进制'编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆