gpt4 book ai didi

python - 将字符串打印为十六进制文字 python

转载 作者:太空宇宙 更新时间:2023-11-03 11:30:21 24 4
gpt4 key购买 nike

我有很多预先存在的代码将字节数组视为字符串,即

In [70]: x = '\x01\x41\x42\x43'

哪个 python 总是打印为:

In [71]: x
Out[71]: '\x01ABC'

这让调试变得很痛苦,因为我打印的字符串看起来不像我代码中的文字。如何将字符串打印为十六进制文字?

最佳答案

对于跨版本兼容的解决方案,请使用 binascii.hexlify :

>>> import binascii
>>> x = '\x01\x41\x42\x43'
>>> print x
ABC
>>> repr(x)
"'\\x01ABC'"
>>> print binascii.hexlify(x)
01414243

由于 .encode('hex') 是对 encode 的误用,已在 Python 3 中删除:

Python 3.3.1
Type "help", "copyright", "credits" or "license" for more information.
>>> '\x01\x41\x42\x43'.encode('hex')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
LookupError: unknown encoding: hex

关于python - 将字符串打印为十六进制文字 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21947035/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com