-3

My question is about how to make the compiler treats my string as an executable statement, consider my string mystr='1+2+3', now the question is what's the code to put in function func so when I execute the following command func(mystr) I get 6 on my screen.

Mehdi
  • 41
  • 9

3 Answers3

3

Using exec() for more than just expression strings:

def func(mystr):
    exec(mystr)

func("mystr='1+2+3';print(mystr)")
  • What's the difference between eval() and exec()? – francisco sollima Sep 01 '17 at 15:24
  • @franciscosollima [exec()](https://docs.python.org/3/library/functions.html#exec) take any Python code (sentences) while [eval()](https://docs.python.org/3/library/functions.html#eval) just expressions. The doc linked is clear ;) –  Sep 01 '17 at 15:28
0

eval(mystr).

Documentation here.

Karl Reid
  • 2,147
  • 1
  • 10
  • 16
0

You can use eval(mystr).

 print eval('1+2+3')

gives you 6

sxzhangzsx
  • 65
  • 9