简体   繁体   English

如何将字符串转换为 Python 中的 function?

[英]How can I convert a string to a function in Python?

I have a function that I have as a string as follows:-我有一个 function 作为字符串,如下所示:-

"def tree(inp):\n\tif inp = 'hello':\n\t\tprint('hello')\n\telse:\n\t\tprint('fake news')"

I want this function to save properly as a function as follows:我希望这个 function 正确保存为 function,如下所示:

def tree(inp):
    if inp == 'hello':
        print('hello')
    else:
        print('fake news')

How can I take this string and save it as a function like this without constant copy pasting?如何获取此字符串并将其另存为 function 像这样,无需不断复制粘贴?

Your string itself contains the syntax error;您的字符串本身包含语法错误; you use = where you should have used == .你使用=你应该使用==的地方。

Having fixed that, you can use exec :修复后,您可以使用exec

>>> fstr = "def tree(inp):\n\tif inp == 'hello':\n\t\tprint('hello')\n\telse:\n\t\tprint('fake news')"
>>> exec(fstr)
>>> tree("hello")
hello
>>> tree("bye")
fake news

This can be it:这可以是:

def tree(inp):
    if inp = 'hello':
        print('hello')
    else:
        print('fake news')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM