-3

Is it possible to run a String text?

Example:

str = "print(2+4)"

Something(str)

Output: 6

Basically turning a string into code, and then running it.

CY83
  • 85
  • 7
  • While it's possible, it's generally not a good solution in basic applications unless you have no other options. – Joffan May 03 '21 at 14:56

2 Answers2

1

Use exec as it can dynamically execute code of python programs.

strr = "print(2+4)"
exec(strr)

>> 6

I will not recommend you to use exec because:

  • When you give your users the liberty to execute any piece of code with the Python exec() function, you give them a way to bend the rules.
  • What if you have access to the os module in your session and they borrow a command from that to run? Say you have imported os in your code.
Hamza usman ghani
  • 2,264
  • 5
  • 19
0

Sure is, looks like your "Something" should be exec.

str = "print(2+4)"

exec(str)

Check out this previous question for more info: How do I execute a string containing Python code in Python?