Python arrays and sting formatting options

Marc 'BlackJack' Rintsch bj_666 at
Tue Sep 30 07:54:03 CEST 2008

On Tue, 30 Sep 2008 03:56:03 +0200, Ivan Reborin wrote:

> a = 2.000001
> b = 123456.789
> c = 1234.0001
> d = 98765.4321
> # same as above except for d
> print (3 * '%12.3f') % (a, b, c)
> #this works beautifully
> How to add d at the end but with a different format now, since I've
> "used" the "format part" ?
> Again, my weird wishful-thinking code: print (3*'%12.3f', '%5.3f')
> %(a,b,c),d

Maybe you should stop that wishful thinking and programming by accident 
and start actually thinking about what the code does, then it's easy to 
construct something working yourself.

The ``%`` operator on strings expects a string on the left with format 
strings in it and a tuple with objects to replace the format strings 
with.  So you want

'%12.3f%12.3f%12.3f%5.3f' % (a, b, c, d)

But without repeating the '%12.3f' literally.  So you must construct that 
string dynamically by repeating the '%12.3f' and adding the '%5.3f':

In [27]: 3 * '%12.3f'
Out[27]: '%12.3f%12.3f%12.3f'

In [28]: 3 * '%12.3f' + '%5.3f'
Out[28]: '%12.3f%12.3f%12.3f%5.3f'

Now you can use the ``%`` operator on that string:

In [29]: (3 * '%12.3f' + '%5.3f') % (a, b, c, d)
Out[29]: '       2.000  123456.789    1234.00098765.432'

(I guess there should be at least a space before the last format string.)

This time you *have* to put parenthesis around the construction of the 
format string BTW because ``%`` has a higher priority than ``+``.  So 
implicit parentheses look like this:

    3 * '%12.3f' + '%5.3f' % (a, b, c, d)
<=> 3 * '%12.3f' + ('%5.3f' % (a, b, c, d))

And there are of course not enough formatting place holders for four 
objects in '%5.3f'.

It's also important to learn why your wrong codes fail.  In your wishful 
thinking example you will get a `TypeError` saying "unsupported operand 
type(s) for %: 'tuple' and 'tuple'".  That's because on the left side of 
the ``%`` operator you wrote a tuple:

In [34]: (3 * '%12.3f', '%5.3f')
Out[34]: ('%12.3f%12.3f%12.3f', '%5.3f')

	Marc 'BlackJack' Rintsch

More information about the Python-list mailing list