python中十六进制流中的格式字符串

时间:2018-10-11 03:53:51

标签: python

我使用Windows 7,python 2.7。

我想将字符串格式化为十六进制。 例如,如果string = '123456 我必须转换为\x12\x34\x56

我已经尝试过但是失败了:

string = '123456'
b'\x%s\x%s\x%s' % string[0:2], string[2:4], string[4:6]

1 个答案:

答案 0 :(得分:1)

您可以使用bytearray.fromhex()方法:

>>> bytearray.fromhex('123456')
bytearray(b'\x124V') # which is the same as b'\x12\x34\x56'