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"]
for item in g_list:
If you really need a
>>> g_list = ["print('Wow!')\n", "print('Great!')\n", "print('Epic!')\n"] >>> old_print = print >>> def print(s): # redefining the built-in print function! terrible idea ... global catstr ... catstr += s ... >>> catstr = "" >>> for s in g_list: exec(s) ... >>> catstr 'Wow!Great!Epic!' >>> print = old_print # Don't forget this step!
This is completely immoral, and I did not advise you to do it. I only said you can do it.
To stress the inadvisability of this plan:
exec should be used rarely; it is dangerous; reassigning the names of built-in functions to different functions should be done very rarely; it is dangerous. Doing both in the same code could really ruin your day, especially after a maintenance programmer edits your code "just a little," without realizing the potential impact.