Python 3 字符串转十六进制

发布于 2024-08-23 18:26:24 字数 423 浏览 6 评论 0原文

在 Python 2 中,这些都有效:

>>> "hello".encode("hex")
'68656c6c6f'
>>> b"hello".encode("hex")
'68656c6c6f'
>>> u"hello".encode("hex")
'68656c6c6f'

但是在 Python 3 中:

>>> "hello".encode("hex")
LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs

How to conversion string to hex in Python 3?

In Python 2 these all worked:

>>> "hello".encode("hex")
'68656c6c6f'
>>> b"hello".encode("hex")
'68656c6c6f'
>>> u"hello".encode("hex")
'68656c6c6f'

But in Python 3:

>>> "hello".encode("hex")
LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs

How to convert string to hex in Python 3?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

淡紫姑娘! 2024-08-30 18:26:24

hex 编解码器已在 3.x 中被删除。使用 binascii 代替:

>>> binascii.hexlify(b'hello')
b'68656c6c6f'

The hex codec has been chucked in 3.x. Use binascii instead:

>>> binascii.hexlify(b'hello')
b'68656c6c6f'
无可置疑 2024-08-30 18:26:24

在 Python 3.5+ 中,将字符串编码为字节并使用 hex() 方法,返回一个字符串。

s = "hello".encode("utf-8").hex()
s
# '68656c6c6f'

可以选择将字符串转换回字节:

b = bytes(s, "utf-8")
b
# b'68656c6c6f'

In Python 3.5+, encode the string to bytes and use the hex() method, returning a string.

s = "hello".encode("utf-8").hex()
s
# '68656c6c6f'

Optionally convert the string back to bytes:

b = bytes(s, "utf-8")
b
# b'68656c6c6f'
酒儿 2024-08-30 18:26:24

在 Python 3.5 及更高版本中执行此操作的最简单方法是:

>>> 'halo'.encode().hex()
'68616c6f'

如果使用 utf-8 字符手动将字符串输入 Python 解释器 ,您可以通过在字符串前键入 b 来更快地完成此操作:

>>> b'halo'.hex()
'68616c6f'

Python 2.x 中的等效项:

>>> 'halo'.encode('hex')
'68616c6f'

The easiest way to do it in Python 3.5 and higher is:

>>> 'halo'.encode().hex()
'68616c6f'

If you manually enter a string into a Python Interpreter using the utf-8 characters, you can do it even faster by typing b before the string:

>>> b'halo'.hex()
'68616c6f'

Equivalent in Python 2.x:

>>> 'halo'.encode('hex')
'68616c6f'
沒落の蓅哖 2024-08-30 18:26:24

您已经得到了一些很好的答案,但我认为您可能也对一些背景感兴趣。

首先你错过了引号。应该是:

"hello".encode("hex")

其次,这个编解码器还没有移植到Python 3.1。请参阅此处。他们似乎还没有决定这些编解码器是否应该包含在 Python 3 中或以不同的方式实现。

如果您查看该错误附加的 diff 文件,您可以看到建议的实现方法它:

import binascii
output = binascii.b2a_hex(input)

You've already got some good answers, but I thought you might be interested in a bit of the background too.

Firstly you're missing the quotes. It should be:

"hello".encode("hex")

Secondly this codec hasn't been ported to Python 3.1. See here. It seems that they haven't yet decided whether or not these codecs should be included in Python 3 or implemented in a different way.

If you look at the diff file attached to that bug you can see the proposed method of implementing it:

import binascii
output = binascii.b2a_hex(input)
南烟 2024-08-30 18:26:24

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'

它有帮助。 :)

binascii methodes are easier by the way

>>> 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'

Hope it helps. :)

和我恋爱吧 2024-08-30 18:26:24

在 Python 3 中,所有字符串都是 unicode。通常,如果将 unicode 对象编码为字符串,则使用 .encode('TEXT_ENCODING'),因为 hex 不是文本编码,因此应该使用 codecs.encode() 处理任意编解码器。例如:

>>>> "hello".encode('hex')
LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs
>>>> import codecs
>>>> codecs.encode(b"hello", 'hex')
b'68656c6c6f'

同样,由于“hello”是unicode,因此在编码为十六进制之前需要将其指示为字节字符串。这可能更符合您使用 encode 方法的原始方法。

binascii.hexlifycodecs.encode 之间的区别如下:

  • binascii.hexlify。十六进制化

    二进制数据的十六进制表示。

    返回值是一个字节对象。

    类型:builtin_function_or_method

  • codecs.encode

    编码(obj, [编码[,错误]]) ->对象

    使用注册用于编码的编解码器对 obj 进行编码。编码默认值
    为默认编码。可能会给出错误来设置不同的错误
    处理方案。默认值为“严格”,这意味着会出现编码错误
    值错误。其他可能的值是“忽略”、“替换”和
    'xmlcharrefreplace' 以及任何其他注册名称
    codecs.register_error 可以处理 ValueErrors。

    类型:builtin_function_or_method

In Python 3, all strings are unicode. Usually, if you encode an unicode object to a string, you use .encode('TEXT_ENCODING'), since hex is not a text encoding, you should use codecs.encode() to handle arbitrary codecs. For example:

>>>> "hello".encode('hex')
LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs
>>>> import codecs
>>>> codecs.encode(b"hello", 'hex')
b'68656c6c6f'

Again, since "hello" is unicode, you need to indicate it as a byte string before encoding to hexadecimal. This may be more inline with what your original approach of using the encode method.

The differences between binascii.hexlify and codecs.encode are as follow:

  • binascii.hexlify

    Hexadecimal representation of binary data.

    The return value is a bytes object.

    Type: builtin_function_or_method

  • codecs.encode

    encode(obj, [encoding[,errors]]) -> object

    Encodes obj using the codec registered for encoding. encoding defaults
    to the default encoding. errors may be given to set a different error
    handling scheme. Default is 'strict' meaning that encoding errors raise
    a ValueError. Other possible values are 'ignore', 'replace' and
    'xmlcharrefreplace' as well as any other name registered with
    codecs.register_error that can handle ValueErrors.

    Type: builtin_function_or_method

北方的巷 2024-08-30 18:26:24

base64.b16encode 和 < a href="http://docs.python.org/dev/library/base64.html#base64.b16decode" rel="nofollow noreferrer">base64.b16decode 将字节转换为以及十六进制并适用于所有 Python 版本。 编解码器方法也可以工作,但在 Python 3 中不太简单。

base64.b16encode and base64.b16decode convert bytes to and from hex and work across all Python versions. The codecs approach also works, but is less straightforward in Python 3.

失与倦" 2024-08-30 18:26:24

还有另一种方法:

s = 'hello'

h = ''.join([hex(ord(i)) for i in s]);

# outputs: '0x680x650x6c0x6c0x6f'

这基本上将字符串拆分为字符,通过 hex(ord(char)) 进行转换,然后将字符重新连接在一起。如果您想要不带前缀 0x 的结果,请执行以下操作:

h = ''.join([str(hex(ord(i)))[2:4] for i in s]);

# outputs: '68656c6c6f'

使用 Python 3.5.3 进行测试。

Yet another method:

s = 'hello'

h = ''.join([hex(ord(i)) for i in s]);

# outputs: '0x680x650x6c0x6c0x6f'

This basically splits the string into chars, does the conversion through hex(ord(char)), and joins the chars back together. In case you want the result without the prefix 0x then do:

h = ''.join([str(hex(ord(i)))[2:4] for i in s]);

# outputs: '68656c6c6f'

Tested with Python 3.5.3.

明月夜 2024-08-30 18:26:24

str 到十六进制:

>>> "hello".encode().hex()
'68656c6c6f'

字节到十六进制:

>>> b"hello".hex()
'68656c6c6f'

来自十六进制的字节:

>>> bytes.fromhex("68656c6c6f")
b'hello'

来自十六进制的 str:

>>> bytes.fromhex("68656c6c6f").decode()
'hello'

str to hex:

>>> "hello".encode().hex()
'68656c6c6f'

bytes to hex:

>>> b"hello".hex()
'68656c6c6f'

bytes from hex:

>>> bytes.fromhex("68656c6c6f")
b'hello'

str from hex:

>>> bytes.fromhex("68656c6c6f").decode()
'hello'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文