I am writing a python script which contains a list containing python print statements as a string. In my function, I am using a for loop to run exec function to run those statements.
Here is my function:
g_list = ["print('Wow!')\n", "print('Great!')\n", "print('Epic!')\n"]
def run_statements():
for item in g_list:
exec(item)
When I run run_statements() function, I get the following output:
Wow!
Great!
Epic!
Basically, I want to save the output as a string so that later, I can save it to my database.
Does anyone have any idea how can I do it?
EDIT: At the following question: python: get the print output in an exec statement He is trying to get output, My question is different in a way that I am trying to get output as a string
printis to send text somewhere, not to save it in memory. If you want to save that as a string, you should simply do so, and then print it when appropriate. Also, it's likely thatexecis the wrong approach for whatever goal you're trying to achieve.. So you want:"Wow!\nGreat!\nEpic\n"`?