Home >Backend Development >Python Tutorial >How Can I Execute Python Code Stored in a String?
Executing Python Code Stored in a String
To execute a string containing Python code in Python, you can use either exec or eval, depending on your specific needs.
Using exec
For statements, use exec(string) (Python 3) or exec string (Python 2):
my_code = 'print("Hello world")' exec(my_code)
This will execute the statement "print('Hello world')" and output "Hello world".
Using eval
When you need the value of an expression, use eval(string):
x = eval("2+2")
This will evaluate the expression "2 2" and assign its value (4) to the variable x.
Caution
It's important to note that executing code stored in a string should be used with caution. It can be slow, can lead to security risks if the code is obtained from an untrusted source, and is generally considered poor programming practice. Consider using higher-order functions or other alternatives to avoid the need for executing strings of code.
The above is the detailed content of How Can I Execute Python Code Stored in a String?. For more information, please follow other related articles on the PHP Chinese website!