-2

Possible Duplicate:
How can I assign the value of a variable using eval in python?

i want to assign a value to a variable that is inside of a string using python

so suppose

y = 'x  = 5' 
eval(y) # does not work

I want something that evaluates this expression so that x = 5 in python

Community
  • 1
  • 1

3 Answers3

1

Try exec instead:

In [8]: y = 'x  = 5'

In [9]: exec(y)

In [10]: x
Out[10]: 5

However as with eval, I imagine there are security concerns here (see this article, for instance), so you may want to approach from a different angle if possible. As for why eval doesn't work, it is because it is evaluating the string as if it were a Python expression. Therefore when you say x = 5, there is no return result. exec on the other hand will execute the statement, and in this case it will set x = 5 in your program.

RocketDonkey
  • 36,383
  • 7
  • 80
  • 84
1

You can use the exec statement for this:

exec y

(In Python 3, it's a function, not a statement.)

However, you probably shouldn't. If you do this with user-input text, it is a security risk. It also can do things you might not expect, depending on what scope you exec the code in. See the documentaton for more info. There is usually a better way to do whatever you want to do than using exec.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
0

You are looking for exec.

y = 'x  = 5' 
exec(y)
print x
BoppreH
  • 8,014
  • 4
  • 34
  • 71