Python Hex Font

How to convert decimal to hexadecimal in the following format (at least two digits, with zero addition, without the 0x prefix)?

Input: 255 Output: ff

Input: 2 Output: 02

I tried hex(int)[2:] , but it seems to display the first example, but not the second.

+43
python hex
Feb 03 '13 at 22:33
source share
3 answers

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' 
+96
Feb 03 '13 at 22:34
source share

I think this is what you want:

 >>> def twoDigitHex( number ): ... return '%02x' % number ... >>> twoDigitHex( 2 ) '02' >>> twoDigitHex( 255 ) 'ff' 
+15
Feb 03 '13 at 22:58
source share

The first answer is the best, but I have an archaic answer, but functional

 >>> "".join(list(hex(255))[2:]) 'ff' 
-7
01 Oct '14 at 18:47
source share



All Articles