83

How to convert decimal to hex in the following format (at least two digits, zero-padded, without an 0x prefix)?

Input: 255 Output:ff

Input: 2 Output: 02

I tried hex(int)[2:] but it seems that it displays the first example but not the second one.

VikkyB
  • 1,440
  • 4
  • 16
  • 26
  • 1
    [What have you tried?](http://whathaveyoutried.com) Why I downvoted this question: http://meta.stackexchange.com/a/149138/133242 – Matt Ball Feb 03 '13 at 22:34
  • I tried hex(int)[2:] but it seems that it displays the first example but not the second one. – VikkyB Feb 03 '13 at 22:35
  • The question and the answers are less useful without an explicit statement of what specifically "the following format" means. Probably "at least two digits, zero-padded, without an 0x prefix"? – LarsH Apr 06 '17 at 13:22
  • Possible duplicate of [Decorating Hex function to pad zeros](https://stackoverflow.com/questions/12638408/decorating-hex-function-to-pad-zeros) – user202729 May 01 '20 at 14:31

3 Answers3

162

Use the format() function with a '02x' format.

>>> format(255, '02x')
'ff'
>>> format(2, '02x')
'02'

The 02 part tells format() to use at least 2 digits and to use zeros to pad it to length, x means lower-case hexadecimal.

The Format Specification Mini Language also gives you X for uppercase hex output, and you can prefix the field width with # to include a 0x or 0X prefix (depending on wether you used x or X as the formatter). Just take into account that you need to adjust the field width to allow for those extra 2 characters:

>>> format(255, '02X')
'FF'
>>> format(255, '#04x')
'0xff'
>>> format(255, '#04X')
'0XFF'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I'm having an issue where the hexadecimal prefix will have a capital "X" if set the format to use uppercase hex output. This doesn't seem to be the case in your example. Is this just an issue with my local version of Python? I'm using version 2.7.9. – jwp36 Apr 29 '15 at 22:44
  • @jwp36: no, it was a mistake in my answer, now corrected. My apologies. – Martijn Pieters Apr 30 '15 at 07:58
  • 4
    to specify the format in the output string `'{:02x}'.format(255)` – JuanPablo Apr 16 '17 at 02:14
  • 1
    @JuanPablo: only do that in a *larger string*. Using `str.format()` just to have it parse out a single slot is making Python do extra work (as internally this still uses `format(255, '02x')` for that one slot). – Martijn Pieters Apr 16 '17 at 09:15
26

I think this is what you want:

>>> def twoDigitHex( number ):
...     return '%02x' % number
... 
>>> twoDigitHex( 2 )
'02'
>>> twoDigitHex( 255 )
'ff'
-8

Another solution is:

>>> "".join(list(hex(255))[2:])
'ff'

Probably an archaic answer, but functional.

Brandon Zamudio
  • 2,853
  • 4
  • 18
  • 34
TeNeX
  • 13