eval syntax problem

Bengt Richter bokr at oz.net
Wed Nov 17 06:22:25 EST 2004


On Wed, 17 Nov 2004 09:53:12 +0100, Matthias Teege <matthias-dated at mteege.de> wrote:

>
>Moin,
>
>what is wrong with
>
>eval('print %s %s %s' % ('%s', '%', 'foo'))
print is a statement, which eval does not like. Use exec for statements,
but it is usually a sign that you haven't yet learned a better way of
doing something if you are a newbie and resorting to eval or exec ;-)

>
>I try to pass a format string to an assignment. Like this
>
>fmt='%.2f'
>a=1
>b="fmt %" % a

 >>> fmt = '%.2f'
 >>> a=1
 >>> b="fmt %" % a
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
 ValueError: incomplete format

Did you not understand that message?
It means that "fmt %" is missing something, which makes it incomplete ;-)
If you look in docs, you can find how to make formats. The one in fmt is ok.
So what you want to do is use that in a normal format % stuff_to_format expression:

 >>> b=fmt % a
 >>> a
 1
 >>> b
 '1.00'

You could complete the format in the error, and try again.
(interactively, you can just type the expression without assigning its value,
that way the interepreter will show a string representation of the result (unless
it's None, in which case it doesn't print anything).

 >>> "fmt %" % a
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
 ValueError: incomplete format
 >>> "fmt %s" % a
 'fmt 1'
 >>>

Regards,
Bengt Richter



More information about the Python-list mailing list