我正在尝试运行此代码,但似乎exec()没有执行函数内的字符串:
def abc(xyz):
for i in fn_lst:
s = 'temp=' + i + '(xyz)'
exec(s)
print (temp)
abc('avdfbafadnf')
Run Code Online (Sandbox Code Playgroud)
我收到的错误:
NameError Traceback (most recent call last)
<ipython-input-23-099995c31c78> in <module>()
----> 1 abc('avdfbafadnf')
<ipython-input-21-80dc547cb34f> in abc(xyz)
4 s = 'temp=' + i + '(word)'
5 exec(s)
----> 6 print (temp)
NameError: name 'temp' is not defined
Run Code Online (Sandbox Code Playgroud)
fn_lst 是一个函数名称列表,即: ['has_at', 'has_num' ...]
exec()如果可能,请让我知道在这种情况下的替代方案。