简体   繁体   English

如何使用 exec() 将字符串值分配给变量?

[英]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 .我正在尝试使用exec将一个未知的字符串值(如“M10”或类似的东西)分配给一个未知的变量名。 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 .它抛出这个错误: NameError: name 'm10' is not defined

As soon as I change the value to 10 for example, it works totally fine.例如,一旦我将值更改为10 ,它就可以正常工作。

What am I missing here?我在这里错过了什么?

quotes around m10, it thinks you're trying to assign a variable to test在 m10 周围引用,它认为你正在尝试分配一个变量来测试

value = "'m10'"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM