In this tutorial, we will show you how to execute strings as Python commands. This allows us to write dynamic strings using f-strings and execute them as commands in Python. This can be done with the exec()
method as we can see with a simple example below.
import pandas as pd # Let's create a pandas data frame df = pd.DataFrame({'Col_1':[1,2,3,4,5], 'Col_2':['A','B','C','D','E']}) df
Now, we will create the same data frame but this time by running it as a string.
df_string = 'df = pd.DataFrame({"Col_1":[1,2,3,4,5],"Col_2":["A","B","C","D","E"]})' exec(df_string) df
Finally, if we would like to run an expression we should use the eval()
method. For example:
eval("5 + 10")
15
Or,
eval("sum([1, 2, 3])")
6