2

是否有一种相当简单的方法可以在 python 中将十六进制整数转换为十六进制字符串?例如,我有0xa1b2c3并且我想要"0xa1b2c3". 如果我使用 str(),它会自动转换为以 10 为底,然后我无法将其转换回来,因为那时它是一个字符串。

4

2 回答 2

5

为什么不直接做hex()

>>> testNum = 0xa1b2c3
>>> hex(testNum)
    '0xa1b2c3'
>>> test = hex(testNum)
>>> isinstance(test, str)
    True

hex返回一个字符串表示。看help(hex)

hex(...)
    hex(number) -> string

    Return the hexadecimal representation of an integer or long integer.
于 2013-07-05T19:47:03.730 回答
2

使用hex

>>> x = 0xa1b2c3
>>> hex(x)
'0xa1b2c3'

字符串格式

>>> "{:#x}".format(x)
'0xa1b2c3'

格式

>>> format(x, '#x')
'0xa1b2c3'
于 2013-07-05T19:46:59.360 回答