[Tutor] String formatting hex numbers

Alan Gauld alan.gauld at btinternet.com
Sun May 31 02:24:39 CEST 2009

"Tony Cappellini" <cappy2112 at gmail.com> wrote

> sys.stdout.write( "\r%-8s ... 0x%08X->0x%08X " % ( descr,
> long(startAddr), long(endAddr) )
> Why are these displayed with a leading negative sign (between the 0x
> and the actual number)- as seen below?
> 0x-1BFFF400 to 0x-1BFFF000

Because they are negative values and the leading 0x is a sting 
hard coded before the number. Let me rework the example to 
make that clearer:

>>> "HEX:%0X" % -29

I replaced 0x with HEX: and useed a negative decimal number 
as input. Now you can see my string (HEX:) followed by the 
formatted hex number with the negative sign correctly placed
before the digits.

The problem is that Pythons string formatting doesn't know 
about prepending 0x to numbers. You need to use the hex 
function for that:

>>> hex(-27)

So the format string becomes:

>>> "HEX:%s" % hex(-29)

And all is as expected.


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list