Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (45.3k points)

How do I execute a string containing Python code in Python?

1 Answer

0 votes
by (16.8k points)

For statements, use exec(string) (Python 2/3) or exec string (Python 2):

>>> mycode = 'print "hello world"'

>>> exec(mycode)

Hello world

When you need the value of an expression, use eval(string):

>>> x = eval("2+2")

>>> x

4

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 22, 2019 in Python by Sammy (47.6k points)

Browse Categories

...