6
a = 1
print hex(a)

The above gives me the output: 0x1

How do I get the output as 0x01 instead?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
heethesh
  • 351
  • 1
  • 5
  • 11
  • possible duplicate of [Python string formatting](http://stackoverflow.com/questions/543399/python-string-formatting) – ivan_pozdeev Feb 22 '15 at 07:29

6 Answers6

14

You can use format :

>>> a = 1
>>> '{0:02x}'.format(a)
'01'
>>> '0x{0:02x}'.format(a)
'0x01'
Mazdak
  • 105,000
  • 18
  • 159
  • 188
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
3
>>> format(1, '#04x') 
'0x01'
Urban48
  • 1,398
  • 1
  • 13
  • 26
2
print "0x%02x"%a

x as a format means "print as hex".
02 means "pad with zeroes to two characters".

Mazdak
  • 105,000
  • 18
  • 159
  • 188
khelwood
  • 55,782
  • 14
  • 81
  • 108
2

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.

Sniggerfardimungus
  • 11,583
  • 10
  • 52
  • 97
1

You can use format:

>>> "0x"+format(1, "02x")
'0x01'
runDOSrun
  • 10,359
  • 7
  • 47
  • 57
0

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

Intrastellar Explorer
  • 3,005
  • 9
  • 52
  • 119