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

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

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


当前回答

我把这个加起来,因为有时候你只想要个位数表示

(x可以是小写字母'x',也可以是大写字母'x',选择决定输出的字母是大写还是小写。):

'{:x}'.format(15)
> f

现在有了新的f "格式字符串,你可以做:

f'{15:x}'
> f

要添加0填充,您可以使用0>n:

f'{2034:0>4X}'
> 07F2

注意:f'{15:x}'中的首字母'f'表示格式字符串

其他回答

(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'

使用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'

注意,对于大值,hex()仍然有效(其他一些答案不适用):

x = hex(349593196107334030177678842158399357)
print(x)

Python 2: 0x4354467b746f6f5f736d616c3f7dl 蟒蛇3:0x4354467b746f6f5f736d616c3f7d

对于解密的RSA消息,可以执行以下操作:

import binascii

hexadecimals = hex(349593196107334030177678842158399357)

print(binascii.unhexlify(hexadecimals[2:-1])) # python 2
print(binascii.unhexlify(hexadecimals[2:])) # python 3

那么hex()呢?

hex(255)  # 0xff

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

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