Integer to Hexadecimal Conversion in Python

后端 未结 6 1714
执念已碎
执念已碎 2021-01-13 11:37
a = 1
print hex(a)

The above gives me the output: 0x1

How do I get the output as 0x01 instead?

6条回答
  •  执笔经年
    2021-01-13 12:15

    Try:

    print "0x%02x" % a
    

    It's a little hairy, so let me break it down:

    The first two characters, "0x" are literally printed. Python just spits them out verbatim.

    The % tells python that a formatting sequence follows. The 0 tells the formatter that it should fill in any leading space with zeroes and the 2 tells it to use at least two columns to do it. The x is the end of the formatting sequence and indicates the type - hexidecimal.

    If you wanted to print "0x00001", you'd use "0x%05x", etc.

提交回复
热议问题