0 votes
1 view
in Python by (26.6k 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
0 answers
0 votes
1 answer
asked Jul 22, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
+1 vote
2 answers
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...