我想取一个整数(这将是<= 255),以十六进制字符串表示

例:我想传入65并得到'\x41',或者255并得到'\xff'。

我尝试过用struct.pack('c',65)这样做,但它会阻塞任何超过9的东西,因为它想要接受单个字符串。


当前回答

那么hex()呢?

hex(255)  # 0xff

如果你真的想要有\在前面,你可以这样做:

print '\\' + hex(255)[1:]

其他回答

这将把一个整数转换成带有0x前缀的2位十六进制字符串:

strHex = "0x%0.2X" % integerVariable

那么hex()呢?

hex(255)  # 0xff

如果你真的想要有\在前面,你可以这样做:

print '\\' + hex(255)[1:]
(int_variable).to_bytes(bytes_length, byteorder='big'|'little').hex()

例如:

>>> (434).to_bytes(4, byteorder='big').hex()
'000001b2'
>>> (434).to_bytes(4, byteorder='little').hex()
'b2010000'

对于Python >= 3.6,使用f-string格式:

>>> x = 114514
>>> f'{x:0x}'
'1bf52'
>>> f'{x:#x}'
'0x1bf52'

Try:

"0x%x" % 255 # => 0xff

or

"0x%X" % 255 # => 0xFF

Python文档说:“把这个放在你的枕头下面:http://docs.python.org/library/index.html”