python 3: string to hex, hex to format

Viewed 21556

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?

4 Answers

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

Related