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

Grant Edwards invalid at invalid.invalid
Fri Nov 5 16:10:29 EDT 2010


On 2010-11-05, Tim Chase <python.list at tim.thechases.com> wrote:
> 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.

I think "0x%02x" % 10 is a bit more readable, but it accomplishes the
same thing -- you just don't have to do the mental math to add the
prefix width to the number of desired hex digits in the output.

-- 
Grant Edwards               grant.b.edwards        Yow! Quick, sing me the
                                  at               BUDAPEST NATIONAL ANTHEM!!
                              gmail.com            



More information about the Python-list mailing list