how to define a function from a string using python

后端 未结 4 1022
时光说笑
时光说笑 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:37

    Eval evalutes only expressions, while exec executes statements.

    So you try something like this

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

提交回复
热议问题