Predictive Hacks

How to Execute Strings as Python Commands

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

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.

Python

Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s