1

I have a function that I have as a string as follows :-

"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:

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?

6
  • 1
    Use the eval function? Commented Jul 6, 2020 at 20:00
  • ^ this gives an error 'invalid syntax' Commented Jul 6, 2020 at 20:10
  • 1
    for starters, you are not naming your function. Commented Jul 6, 2020 at 20:20
  • ^ fixed this in the post and in my code. I'm still getting the same error Commented Jul 6, 2020 at 20:50
  • 2
    You would need exec, as a def statement is not an expression (which is what eval expects). Commented Jul 6, 2020 at 20:53

2 Answers 2

1

Your string itself contains the syntax error; you use = where you should have used ==.

Having fixed that, you can use 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
Sign up to request clarification or add additional context in comments.

Comments

0

This can be it :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.