Using %x to format number to hex and number of digits

Tim Chase python.list at
Fri Nov 5 20:52:44 CET 2010

On 11/05/10 13:23, Matty Sarro wrote:
>> I'm currently trying to convert a digit from decimal to hex,
>> however I need the full 4 digit hex form. Python appears to
>> be shortening the form.
>> Example:
>> num = 10
>> num = "%x"%(num)
>> print(num)
>>>> a
>> num = 10
>> num = "%#x"%(num)
>> print(num)
>>>> 0xa
>> I need it to output as 0x0a, and the exercise is requiring
>> me to use %x to format the string. Any help would be
>> appreciated.

Though it feels hokey to me, using

   "%#04x" % 10

works for me.  The "#" adds the "0x" prefix (the "alternate 
form"), the "0" pads with zeros, and the "4" is really "2 places 
+ 2 characters for the prefix".  So if you want 4 hex characters 
+ the 2 prefix characters, you'd use "%#06x".  IMHO, this would 
make more sense if it didn't take the 2-character prefix into 
consideration (being written as "%#02x" for a byte or "%#04x" for 
a short), but it's not really a burr in my saddle.


More information about the Python-list mailing list