问题
I am looking for a good way to convert a string into a hex string.
For example:
'\x01\x25\x89'->'0x012589''\x25\x01\x00\x89'->'0x25010089'
Here is what I have come up with:
def to_hex(input_str):
new_str = '0x'
for char in input_str:
new_str += '{:02X}'.format(ord(char))
return new_str
It seems like there is probably a better way to do this that I haven't been able to find yet.
回答1:
You want the binascii module.
>>> binascii.hexlify('\x01\x25\x89')
'012589'
>>> binascii.hexlify('\x25\x01\x00\x89')
'25010089'
回答2:
Just encode to hex:
In [5]: s= "\x01\x25\x89"
In [6]: s.encode("hex")
Out[6]: '012589'
In [7]: s = "\x25\x01\x00\x89"
In [8]: s.encode("hex")
Out[8]: '25010089'
来源:https://stackoverflow.com/questions/34661563/converting-string-into-hex-representation