带有exec函数的NameError

时间:2018-05-17 16:43:21

标签: python

我是Python的新手。我正在尝试应用一些动态函数(startswith()replace(),exec ..)定义为字符串。

我有这段代码:

access_number = 'CF-12345' 
condition = 'str({v}).startswith("CF-", 0)'

result = {}
exec (condition.format(v = access_number)) in r

但我有这个错误:

Traceback (most recent call last):                                                                                                                   
  File "/home/main.py", line 11, in <module>                                                                                                         
    exec (condition.format(v = access_number)) in r                                                                                                  
  File "<string>", line 1, in <module>                                                                                                               
NameError: name 'CF' is not defined  

我不知道我做错了什么。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:-1)

如果您运行

,请尝试使用print语句作为诊断
access_number = 'CF-12345'
condition = 'str({v}).startswith("CF-", 0)'

result = {}
print condition
print condition.format(v=access_number)
exec (condition.format(v = access_number)) in result

输出

str({v}).startswith("CF-", 0)
str(CF-12345).startswith("CF-", 0)
Traceback (most recent call last):
File "stuff.py", line 8, in <module>
exec (condition.format(v = access_number)) in result
File "<string>", line 1, in <module>
NameError: name 'CF' is not defined

注意第二行有str(CF-1234)这是试图从变量CF中减去1234。

access_number = '"CF-12345"'
condition = 'str({v}).startswith("CF-", 0)'

result = {}
exec (condition.format(v = access_number)) in result