Python 3.1.1字符串到十六进制

Stu*_*art 63 python string hex python-3.x

我正在尝试使用,str.encode()但我得到了

>>> "hello".encode(hex)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be string, not builtin_function_or_method
Run Code Online (Sandbox Code Playgroud)

我尝试了很多变种,它们似乎都在Python 2.5.2中工作,所以我需要做些什么才能让它们在Python 3.1中工作?

Ign*_*ams 84

hex编解码器已被卡住在3.x中 binascii改为使用:

>>> binascii.hexlify(b'hello')
b'68656c6c6f'
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,二进制代码在3.2版中卷土重来,[请参阅docs](https://docs.python.org/3/library/codecs.html#binary-transforms) (2认同)
  • 如果我的字符串存储在变量中怎么办? (2认同)
  • 这会产生错误,因为参数必须是类似字节的对象。 (2认同)

Mar*_*ers 23

你已经有了一些很好的答案,但我认为你可能也对一些背景感兴趣.

首先你错过了报价.它应该是:

"hello".encode("hex")
Run Code Online (Sandbox Code Playgroud)

其次,此编解码器尚未移植到Python 3.1.看到这里.似乎他们还没有决定这些编解码器是否应该包含在Python 3中或以不同的方式实现.

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

import binascii
output = binascii.b2a_hex(input)
Run Code Online (Sandbox Code Playgroud)


iMa*_*gur 18

顺便提一下,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'
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.:)


pyl*_*ang 16

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

s = "hello".encode("utf-8").hex()
s
# '68656c6c6f'
Run Code Online (Sandbox Code Playgroud)

(可选)将字符串转换回字节:

b = bytes(s, "utf-8")
b
# b'68656c6c6f'
Run Code Online (Sandbox Code Playgroud)

  • 这是为Python 3字符串变量执行此操作的方法.这里的答案很多都是关于常数的.实用的代码很少. (2认同)

Dev*_*evy 9

在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'
Run Code Online (Sandbox Code Playgroud)

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

binascii.hexlify和之间的差异codecs.encode如下:

  • binascii.hexlify

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

    返回值是一个bytes对象.

    键入:builtin_function_or_method

  • codecs.encode

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

    使用为编码注册的编解码器对obj进行编码.encoding默认为默认编码.可以给出错误以设置不同的错误处理方案.默认为'strict',表示编码错误会引发ValueError.其他可能的值是'ignore','replace'和'xmlcharrefreplace',以及可以处理ValueErrors的codecs.register_error注册的任何其他名称.

    键入:builtin_function_or_method


Gab*_*iel 7

base64.b16encodebase64.b16decode转换数据和接收十六进制和所有Python版本工作.该编解码器的方法也可以,但是在Python 3那么简单.


sim*_*eco 5

在Python 3.x中最简单的方法是:

>>> 'halo'.encode().hex()
'68616c6f'
Run Code Online (Sandbox Code Playgroud)

如果您使用utf-8字符在Python解释器中手动输入字符串,则可以通过b在字符串之前输入以下命令来更快地完成输入:

>>> b'halo'.hex()
'68616c6f'
Run Code Online (Sandbox Code Playgroud)

在Python 2.x中等效:

>>> 'halo'.encode('hex')
'68616c6f'
Run Code Online (Sandbox Code Playgroud)