Error on string formatting

Joshua Macy amused at webamused.com
Tue Feb 8 21:02:49 EST 2000


Judy Hawkins wrote:
> 
> Why this:
> 
> >>> buf = '%0.*f' % 3, 4.1
> Traceback (innermost last):
>   File "<stdin>", line 1, in ?
> TypeError: not enough arguments for format string
> 
> The comparable statement in C works fine, and the Essential Reference
> says I can do this kind of asterisk thing.
> 
> Judy Hawkins
> 
> Sent via Deja.com http://www.deja.com/
> Before you buy.


  Pythons's % operator takes a collection on the right-hand side (either
a tuple or a mapping), with a special dispensation for singletons, so
that you don't have to write, e.g.

>>> print "This %s, but is ugly" % ('works',)
This works, but is ugly
>>> print "This is %s prettier, ne?" % 'much'
This is much prettier, ne?

So, when you have a sequence that you want to pass it, such as 3, 4.1,
you have to make it really a sequence (3, 4.1)

>>>  buf = '%0.*f' % 3, 4.1
  File "<stdin>", line 1
    buf = '%0.*f' % 3, 4.1
    ^
SyntaxError: invalid syntax
>>> buf = '%0.*f' % (3, 4.1)
>>> print buf
4.100
>>> 

  Joshua



More information about the Python-list mailing list