Integer to Hexadecimal Conversion in Python

后端 未结 6 1706
执念已碎
执念已碎 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:19

    Here is f-string variant for Python 3.6+:

    a = 1
    print(f"{a:0>2x}")
    

    Explanation of string formatting:

    • :: format specifier
    • 0: fill (with 0)
    • >: right-align field
    • 2: width
    • x: hex type

    Source: 6.1.3.1 Format Specification Mini-Language

提交回复
热议问题