[Tutor] TypeError: not enough arguments for format string

broek at cc.umanitoba.ca broek at cc.umanitoba.ca
Wed Jul 2 19:15:58 CEST 2008


----- Message from john at fouhy.net ---------
     Date: Wed, 2 Jul 2008 16:49:19 +1200
     From: John Fouhy <john at fouhy.net>


> On 02/07/2008, Christopher Spears <cspears2002 at yahoo.com> wrote:
>>   File "point.py", line 13, in __str__
>>     point_str = "(%f,%f)" % self.x, self.y
>>  TypeError: not enough arguments for format string
>>
>>  Does anyone know what is wrong?  I'm sure it is something obvious,  
>>  but I can't see it.
>
> Hi Christopher,
>
> Here's the short answer: You need to put brackets around "self.x, self.y"
> i.e.     point_str = "(%f,%f)" % (self.x, self.y)
>
> The long answer: Python interprets the statement "point_str =
> "(%f,%f)" % self.x, self.y" as "point_str = ("(%f,%f)" % self.x),
> self.y".  There are two "%f" expressions in the string, but you only
> supplied one argument, self.x.  Thus python tells you that there
> aren't enough arguments.  To deal with this, you need to supply the
> arguments as a tuple.


Hi all,

While it is true that you need to put parenthesis around the  
arguments, it isn`t quite the case that they are needed so as to  
provide the arguments as a tuple:

>>> a = 42, 42
>>> type(a)
<type 'tuple'>
>>>

It is the comma, not the parens that make for a tuple. My guess is  
that the parens are needed to disambiguate the end of the arguments as  
the comma can also indicate that another element is to be printed on  
the same line:

>>> print '%s' %42 , 333
42 333
>>>

In a case like

>>> print '%s%s' %42 , 333
...
TypeError: not enough arguments for format string

it would be ambiguous whether 333 was intended as a second formatting  
argument or as a second thing to be printed.

Best,

Brian vdB


More information about the Tutor mailing list