Python arrays and sting formatting options

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Mon Sep 29 20:59:40 EDT 2008


Ivan Reborin:
> Is there a way to just do something like this (not normal syntax, just
> my wishful thinking):
> print 3*'%12.3f' %a,b,c
> (meaning - use this format for the next 3 real numbers that come
> along)

The Python genie grants you that wish. You were almost right:

>>> a = 2.000001
>>> b = 123456.789
>>> c = 1234.0001
>>> print (3 * '%12.3f') % (a, b, c)
       2.000  123456.789    1234.000
>>> print 3 * '%12.3f' % (a, b, c)
       2.000  123456.789    1234.000
>>> print 3 * '%12.3f' % a, b, c
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string

(Note the spaces and parentheses. Python programmers thank you if put
them improving readability a little).

Bye,
bearophile



More information about the Python-list mailing list