0

I have the following code:

a=2
string="a"
b=exec(string)
print(b)

Output:

None

I want b to have the value of 'a' i.e. 2 how can I do that?

vaultah
  • 44,105
  • 12
  • 114
  • 143
Ravi
  • 167
  • 2
  • 12
  • 2
    Could you expand on the *context*; why do you want to do this? – jonrsharpe Jul 02 '18 at 09:49
  • Actually the name 'a' I am getting as input from a file.consider I have many variables and I want to assign 'b' to the value which I get from the file. – Ravi Jul 02 '18 at 09:52
  • 2
    Then in all probability what you actually want is a *dictionary*: `{"a": 2}["a"] == 2`. – jonrsharpe Jul 02 '18 at 09:53

2 Answers2

2

If I understand your case correctly, you want to evaluate some python source from string in context of existing variables. Builtin eval function could be used for that.

a=2
string="a"
b=eval(string)
print(b)

Anyway. Why do you need that? There is better way to do that for sure.

Probably in your case you could use dictionary to remember values instead of separate variables. And after reading "names" from file use this names as dictionary keys.

your_dict = {}
your_dict["a"] = 2
string = "a"
b = your_dict[string]
print(b)
running.t
  • 5,329
  • 3
  • 32
  • 50
1
a=2
string="b=a"
exec(string)
print(b)

exec() just exectues the code in the given string, so the assignment must be done in the string itself.

TheCurl
  • 106
  • 1
  • 2