Issue
I try:
def test(w,sli):
s = "'{0}'{1}".format(w,sli)
exec(s)
return s
print test("TEST12344","[:2]")
its return 'TEST12344'[:2]
How to return value from exec in function
Solution
exec()
doesn't just evaluate expressions, it executes code. You would have to save a reference within the exec()
call.
def test(w, sli):
exec('s = "{}"{}'.format(w, sli))
return s
If you just want to evaluate an expression, use eval()
, and save a reference to the returned value:
def test(w,sli):
s = "'{0}'{1}".format(w,sli)
s = eval(s)
return s
However, I would recommend avoiding exec()
and eval()
in any real code whenever possible. If you use it, make sure you have a very good reason to do so.
Answered By - TigerhawkT3 Answer Checked By - Robin (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.