Hexadecimal integer in Python

a = 1
print hex(a)

The above gives me the result: 0x1

How to get the result as 0x01instead of?

+4
source share
5 answers

You can use format:

>>> a = 1
>>> '{0:02x}'.format(a)
'01'
>>> '0x{0:02x}'.format(a)
'0x01'
+10
source
print "0x%02x"%a

xhow format means "print as hex".
02means pad with zeros up to two characters.

+2
source

Try:

print "0x%02x" % a

, :

"0x" . Python .

% python . 0 , , 2 . X - - hexidecimal.

If you want to print "0x00001", you should use "0x% 05x", etc.

+2
source
>>> format(1, '#04x') 
'0x01'
+2
source

You can use format :

>>> "0x"+format(1, "02x")
'0x01'
+1
source

All Articles