Using %x to format number to hex and number of digits
Tim Chase
python.list at tim.thechases.com
Fri Nov 5 21:22:53 EDT 2010
On 11/05/10 15:10, Grant Edwards wrote:
> On 2010-11-05, Tim Chase<python.list at tim.thechases.com> wrote:
>> On 11/05/10 13:23, Matty Sarro wrote:
>>>> 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.
Which, I confess, is what I usually use because I didn't know
about the "#" until this thread, and just made the assumption
that one can get the zero-padding along with the "alternate form"
in my experimentation this afternoon.
So while it _can_ be done with just variants of the "%x"
place-holder (as suggested by the OP's exercise), at least two of
us on the list prefer to explicitly add the "0x" to the beginning.
-tkc
More information about the Python-list
mailing list