how to define a function from a string using python

后端 未结 4 1017
时光说笑
时光说笑 2020-12-06 17:45

this is my code :

a = \\
\'\'\'def fun():\\n
    print \'bbb\'
\'\'\'
eval(a)

fun()

but it shows error :

Traceback (most r         


        
4条回答
  •  春和景丽
    2020-12-06 18:46

    If your logic is very simple (i.e., one line), you could eval a lambda expression:

    a = eval("lambda x: print('hello {0}'.format(x))")
    a("world") # prints "hello world"
    

    As others have mentioned, it is probably best to avoid eval if you can.

提交回复
热议问题