Search code examples
pythonstringexec

How to assign a string-value to a variable with exec()?


I know there are plenty of these questions already, but I still couldn't figure out a solution for my problem:

I am trying to assign an unknown string value (like "M10" or something similar) to an unknown variable name by using exec. Therefore I tried the following, but it does not work:

name  = "test"
value = "m10"
exec("%s=%s" % (name, value), globals())
exec("{}={}".format(name, value), globals())
print(test)

It throws this error: NameError: name 'm10' is not defined.

As soon as I change the value to 10 for example, it works totally fine.

What am I missing here?


Solution

  • quotes around m10, it thinks you're trying to assign a variable to test

    value = "'m10'"