如何在 Python 3.2 或更高版本中使用“十六进制”编码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12917278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:10:06  来源:igfitidea点击:

How to use the 'hex' encoding in Python 3.2 or higher?

pythonencodingpython-3.xhex

提问by Tim Pietzcker

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

在 Python 2 中,要获取字符串中十六进制数字的字符串表示形式,您可以执行以下操作

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

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

在 Python 3 中,这不再起作用(在 Python 3.2 和 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 answerhere on SO that mentions that the hexcodec 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".

SO上至少有一个答案提到hex编解码器已在 Python 3 中删除。但是,根据文档,它在 Python 3.2 中重新引入,作为“字节到字节映射”。

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.

而且文档也没有提到这一点(至少不是我看过的地方)。我一定错过了一些简单的东西,但我看不到它是什么。

采纳答案by ecatmur

You need to go via the codecsmodule and the hex_codeccodec (or its hexalias if available*):

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

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

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

* 来自文档:“在 3.4 版中更改:恢复二进制转换的别名”

回答by dan04

Using base64.b16encode():

使用base64.b16encode()

>>> import base64
>>> base64.b16encode(b'\x12\x34\x56\x78')
b'12345678'

回答by Mark Tolonen

Yet another way using binascii.hexlify():

另一种使用方式binascii.hexlify()

>>> import binascii
>>> binascii.hexlify(b'\x12\x34\x56\x78')
b'12345678'

回答by iMagur

binasciimethods are easier by the way:

binascii顺便说一下,方法更简单:

>>> import binascii
>>> x=b'test'
>>> x=binascii.hexlify(x)
>>> x
b'74657374'
>>> y=str(x,'ascii')
>>> y
'74657374'
>>> x=binascii.unhexlify(x)
>>> x
b'test'
>>> y=str(x,'ascii')
>>> y
'test'