assign output of print to a variable in python

前端 未结 6 1415
心在旅途
心在旅途 2021-01-15 01:41

i want to know how to assign the output of print to a variable.

so if

mystring = \"a=\\\'12\\\'\"

then

print mys         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-15 02:05

    I believe one of these two things will accomplish what you're looking for:

    The Python exec statement: http://docs.python.org/reference/simple_stmts.html#exec or the Python eval function: http://docs.python.org/library/functions.html#eval

    Both of them let you dynamically evaluate strings as Python code.

    UPDATE:

    What about:

    def calltest(keywordstr):
        return eval("test(" + keywordstr + ")")
    

    I think that will do what you're looking for.

提交回复
热议问题