5

问题:我需要将字符串转换为十六进制,然后格式化十六进制输出。

tmp = b"test"
test = binascii.hexlify(tmp)
print(test) 

输出:b'74657374'


我想将此十六进制输出格式化为:74:65:73:74

我遇到了障碍,不知道从哪里开始。我确实考虑过将输出再次转换为字符串,然后尝试对其进行格式化,但必须有更简单的方法。

任何帮助将不胜感激,谢谢。

==========

操作系统:Windows 7

tmp = "test"
hex = str(binascii.hexlify(tmp), 'ascii')
print(hex)

formatted_hex = ':'.join(hex[i:i+2] for i in range(0, len(hex), 2))
print(formatted_hex

[错误] Traceback(最近一次调用最后一次):文件“C:\pkg\scripts\Hex\hex.py”,第 24 行,十六进制 = str(binascii.hexlify(tmp), 'ascii') TypeError: 'str '不支持缓冲接口

此代码仅在使用 tmp = b'test' 时有效,我需要能够以时尚的方式使用 tmp = importString,因为我从文件顺序中将另一个值传递给它以使我的代码段工作。有什么想法吗?

4

4 回答 4

11
hex = str(binascii.hexlify(tmp), 'ascii')
formatted_hex = ':'.join(hex[i:i+2] for i in range(0, len(hex), 2))

这利用了指定的step参数range(),而不是给出范围内的每个整数,它应该只给出每个第二个整数(对于step=2)。


>>> tmp = "test"
>>> import binascii
>>> hex = str(binascii.hexlify(tmp), 'ascii')
>>> formatted_hex = ':'.join(hex[i:i+2] for i in range(0, len(hex), 2))
>>> formatted_hex
'74:65:73:74'
于 2012-08-20T04:55:39.420 回答
1
>>> from itertools import izip_longest, islice
>>> t = b"test".encode('hex')
>>> ':'.join(x[0]+x[1] for x in izip_longest(islice(t,0,None,2),islice(t,1,None,2)))
'74:65:73:74'
于 2012-08-20T05:14:06.870 回答
0

从 Python 3.8 开始,标准库中提供了此功能:binascii.hexlify有一个新参数sep.

test = binascii.hexlify(tmp, b':')

如果您想要一个文本 ( str) 字符串而不是bytes字符串:

test = binascii.hexlify(tmp, b':').decode('ascii')
于 2021-01-26T18:28:17.607 回答
0

此代码产生预期的输出:

tmp='test'

l=[hex(ord(_))[2:] for _ in tmp]

print(*l,sep=':')

-->74:65:73:74

于 2021-12-07T10:56:50.820 回答