Lets say you got a string representation of a python syntax that you actually want to execute/run not just display it on the console, how do you execute/run such a string code?
print( "print('Hello World')" )
Above code will print print('Hello World') instead of 'Hello World'. Also the code below will display len('Hello World') instead length of the characters as 11.
print( "len('Hello World')" )
There are two function that can help you get the task done. They are the exec and the eval functions. See difference between exec and eval here
# Using exec function
exec( "print('Hello World')" )
exec( '''print( "print('Hello World')" )''' )
# Using eval function
eval( "print('Hello World')" )
eval( '''print( "print('Hello World')" )''' )
print( "len('Hello World')" )
# Using exec function
exec( "len('Hello World')" )
exec( '''len( "print('Hello World')" )''' )
# Using eval function
eval( "len('Hello World')" )
eval( '''len( "print('Hello World')" )''' )
I found this very useful when I want to evaluate a dynamically generated Python expression.
Happy coding.
No comments:
Post a Comment