Question: I need to convert a string into hex and then format the hex output.
tmp = b"test"test = binascii.hexlify(tmp)print(test)
output: b'74657374'
I want to format this hex output to look like this: 74:65:73:74
I have hit a road block and not sure where to start. I did think of converting the output to a string again and then trying to format it but there must be an easier way.
Any help would be appreciated, thanks.
==========
OS: 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
[Error]Traceback (most recent call last):File "C:\pkg\scripts\Hex\hex.py", line 24, in hex = str(binascii.hexlify(tmp), 'ascii')TypeError: 'str' does not support the buffer interface
This code only works when using tmp = b'test' I need be able use tmp = importString in fashion as I'm passing another value to it from a file order for my snippet to work. Any thoughts?
Best Answer
hex = str(binascii.hexlify(tmp), 'ascii')formatted_hex = ':'.join(hex[i:i+2] for i in range(0, len(hex), 2))
This makes use of the step
argument to range()
which specifies that instead of giving every integer in the range, it should only give every 2nd integer (for 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'
>>> 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'
Since Python 3.8, this functionality is available in the standard library: binascii.hexlify
has a new parameter sep
.
test = binascii.hexlify(tmp, b':')
If you want a text (str
) string rather than a bytes
string:
test = binascii.hexlify(tmp, b':').decode('ascii')
This code produces the expected output:
tmp='test'l=[hex(ord(_))[2:] for _ in tmp]print(*l,sep=':')
-->74:65:73:74