eval syntax problem

M

Matthias Teege

Moin,

what is wrong with

eval('print %s %s %s' % ('%s', '%', 'foo'))

I try to pass a format string to an assignment. Like this

fmt='%.2f'
a=1
b="fmt %" % a

Matthias
 
E

Erik Max Francis

Matthias said:
what is wrong with

eval('print %s %s %s' % ('%s', '%', 'foo'))

print is a statement, not an expression, and eval only handles
expressions. Use exec instead.
 
B

Bengt Richter

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
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:
'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).
Traceback (most recent call last):

Regards,
Bengt Richter
 
J

Josiah Carlson

Erik Max Francis said:
print is a statement, not an expression, and eval only handles
expressions. Use exec instead.

What the hell are you talking about? Don't use either eval or exec,
both are remote holes waiting to happen.

Furthermore...
File "<stdin>", line 1
print %s % foo
^
SyntaxError: invalid syntax

That is also incorrect syntax. Seemingly you want to be doing the
equivalent of...

b = '%.2f'%a
Which will just create a string representation of a float to 2 decimal
places of precision.

If you want to do rounding on the object, use round...

b = round(a, 2)


- Josiah
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,211
Messages
2,571,092
Members
47,693
Latest member
david4523

Latest Threads

Top