Decorating Hex function to pad zeros

Use the new .format() string method:

>>> "{0:#0{1}x}".format(42,6)
'0x002a'

Explanation:

{   # Format identifier
0:  # first parameter
#   # use "0x" prefix
0   # fill with zeroes
{1} # to a length of n characters (including 0x), defined by the second parameter
x   # hexadecimal number, using lowercase letters for a-f
}   # End of format identifier

If you want the letter hex digits uppercase but the prefix with a lowercase 'x', you'll need a slight workaround:

>>> '0x{0:0{1}X}'.format(42,4)
'0x002A'

Starting with Python 3.6, you can also do this:

>>> value = 42
>>> padding = 6
>>> f"{value:#0{padding}x}"
'0x002a'

If you don't need to handle negative numbers, you can do

"{:02x}".format(7)   # '07'
"{:02x}".format(27)  # '1b'

Where

  • : is the start of the formatting specification for the first argument {} to .format()
  • 02 means "pad the input from the left with 0s to length 2"
  • x means "format as hex with lowercase letters"

You can also do this with f-strings:

f"{7:02x}"   # '07'
f"{27:02x}"  # '1b'

If just for leading zeros, you can try zfill function.

'0x' + hex(42)[2:].zfill(4) #'0x002a'

How about this:

print '0x%04x' % 42