Use the format() function with the format '02x' .
>>> format(255, '02x') 'ff' >>> format(2, '02x') '02'
Part 02 tells format() use at least 2 digits and use zeros to put it in length, x means a hexadecimal hexadecimal number.
The Mini Language specification format also gives you x for the upper hexadecimal output, and you can prefix the field width with # to include the prefix 0x or 0x (depending on how you used x or x as the formatting). Just keep in mind that you need to adjust the field width to allow these extra 2 characters:
>>> format(255, '02X') 'FF' >>> format(255, '#04x') '0xff' >>> format(255, '#04X') '0XFF'
Martijn Pieters Feb 03 '13 at 22:34 2013-02-03 22:34
source share