[Tutor] Leading zero for hex numbers

Orri Ganel singingxduck at gmail.com
Thu Dec 16 02:44:29 CET 2004


On Wed, 15 Dec 2004 17:47:58 -0800 (PST), Tony Cappellini
<tony at tcapp.com> wrote:
> 
> I'm trying to get Python to automatically print a leading 0 for hex
> numbers, but it only
> seems to work for for decimal numbers.
> 
> print "0x%0X" % 12345
> 
> displays
> 0x3039
> 
> instead of 0x03039
> 
> The Python docs state
> The conversion will be zero padded for numeric values, when a 0 is used as
> a flag between the % and the conversion type.
> 
> Is this expected Python behaviour, or a mistake?
> 
> Sure, I can add some code to calculate the length of the current string to
> decide if a leading 0 is needed., but if I don't have to, I'd rather not.
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

>>> print "0x%0X" % 12345
0x3039
>>> print "0x%0.X" % 12345
0x3039
>>> print "0x%1X" % 12345
0x3039
>>> print "0x%10X" % 12345
0x      3039
>>> print "0x%2X" % 12345
0x3039
>>> print "0x%3X" % 12345
0x3039
>>> print "0x%0.10X" % 12345
0x0000003039
>>> print "0x%0.5X" % 12345
0x03039
>>> print "0x%0.5X" % 123456
0x1E240
>>> print "0x%0X" % 123456
0x1E240
>>> print "0x%0.5X" % 2222
0x008AE
>>> print "0x%0.5X" % 22222
0x056CE
>>> print "0x%0.5X" % 122222
0x1DD6E

Ok, so the character after the % and before the . is the padding
character, and the number after the . and before the X is the minimum
size for the string to be.

So

print "0x%0.5X" % 12345

seems to do what you want.

-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.


More information about the Tutor mailing list