为什么这个exec命令不起作用

时间:2015-05-16 06:44:37

标签: python python-2.7

为什么以下这些陈述给出错误

>>> exec("x={}".format('b'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'b' is not defined

我需要结果

x='b'

1 个答案:

答案 0 :(得分:3)

你应该提供另一对报价

>>> exec("x={}".format("'b'"))
>>> x
'b'

<强>为什么吗

写作时

exec("x={}".format('b'))
你正试着写

x=b

显然python不知道b是什么,除非你之前已经定义过它。

当你写的时候

exec("x={}".format("'b'"))

相同
x='b'
相关问题