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

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

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


当前回答

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

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

其他回答

我想要一个随机整数转换成一个六位数十六进制字符串与#在开始。为了得到这个,我用了

"#%6x" % random.randint(0xFFFFFF)

那么hex()呢?

hex(255)  # 0xff

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

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

使用format(),按照format-examples,我们可以做到:

>>> # format also supports binary numbers
>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'

你可以用另一种表达方式

[in] '%s' % hex(15)
[out]'0xf'

你也可以把任何基数的任何数字转换成十六进制。使用这一行代码,它很容易使用:

十六进制(int x (n,) . replace(“0x”、“”)

你有一个字符串n是你的数字x是这个数字的底。首先,改变它为整数,然后十六进制,但十六进制有0x在它的第一个,所以替换我们删除它。