velkoon
velkoon

Reputation: 962

String is being treated as variable in `eval` statement

I'm trying to do an extremely simple pass-in of a string variable into my eval statement. However, my string is being treated as an undefined variable.

Here is my code:

condition = 'hi'
print(eval("2 + 4 * len(%s)" % (condition)))

Output:

Traceback (most recent call last):
  File "C:\test.py", line 3, in <module>
    print(eval("4 + 3 * len(%s)" % (condition)))
  File "<string>", line 1, in <module>
NameError: name 'hi' is not defined

However, when I define hi as if it were a variable, all the sudden the code compiles and runs:

condition = 'hi'
hi = 'hi'
print(eval("2 + 4 * len(%s)" % (condition)))

Output:

10

What in the world? This seems totally unintuitive to me. Could someone help me define condition in a way that Python does not ask for 'hi' to be defined as well?

Upvotes: 0

Views: 135

Answers (4)

Eric Chancellor
Eric Chancellor

Reputation: 126

You need quotes around %s, like so:

condition = 'hi'
print(eval("2 + 4 * len('%s')" % (condition)))

This way you are passing len() a string 'hi' instead of a variable hi.

Upvotes: 1

almiki
almiki

Reputation: 455

That %s will get replaced with hi. So you are asking python to run the code:

eval("2 + 4 * len(hi)")

len(hi) will look for a variable named "hi". What you want is len('hi') or len(condition). Here are a few alternatives that should work:

# Simplest
print(eval("2 + 4 * len(condition)"))

# Repr gives you the string representation of the object, including quotes
print(eval("2 + 4 * len(%s)" % (repr(condition))))

# Assuming condition doesn't contain '
print(eval("2 + 4 * len('%s')" % (condition))) 

Upvotes: 1

Lante Dellarovere
Lante Dellarovere

Reputation: 1858

you are not passing hi as a string

>>> condition = "'hi'"
>>> print(eval("2 + 4 * len(%s)" % (condition)))
10

Upvotes: 0

Tal Borenstein
Tal Borenstein

Reputation: 1

Basically you're replacing %s with 'hi'.

Try executing len(hi) will result the same NameError exception as hi is not defined.

print(eval("2 + 4 * len(\"%s\")" % condition))

will do the job. screenshot

Upvotes: 0

Related Questions