Reputation: 349
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?
Upvotes: 1
Views: 73
Reputation: 51
This can be it :
def tree(inp):
if inp = 'hello':
print('hello')
else:
print('fake news')
Upvotes: 0
Reputation: 532418
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
Upvotes: 1