-1

so here's the problem:

letsSay = "!math 74*11"
l = letsSay.split("!math ")[1]
formatted = f"{l}"
print(formatted)

it outputs "74*11" instead of doing the operation, how do I make it do the operation first?

Harm
  • 1
  • probably use `eval()` – user1558604 Dec 14 '19 at 21:19
  • Because the output of `split` is a string and not an expression. You can force the evaluation of such string with `eval` function. – Ignacio Vergara Kausel Dec 14 '19 at 21:19
  • 2
    No! Don't use `eval`, and don't recommend `eval`! This is extremely dangerous. – kaya3 Dec 14 '19 at 21:28
  • 1
    This requires parsing your string. 1) detect terms, and convert to the proper type (int, float) 2) detect operators, and convert to proper python operators. Then you'll be able to compute. This is not simple. See [this answer](https://stackoverflow.com/a/1545518/6914989) – FabienP Dec 14 '19 at 21:49

1 Answers1

2

Given the form of the input string, which starts with !math, I believe you are writing a bot for an online chat room. Even if you are not, but especially if you are, do not use eval to compute the result. The eval function is dangerous, because it runs arbitrary code provided as a string; especially when that string comes from an untrusted user on an internet chat room, using eval is like giving your house key to any random stranger who asks for it. This is called remote code execution, and it is a very serious security vulnerability.

The correct solution to your problem is to use a library or API for evaluating mathematical expressions which does not execute arbitrary code as a string. See this other question for examples.

kaya3
  • 47,440
  • 4
  • 68
  • 97
  • what library should I use then? – Harm Dec 14 '19 at 21:47
  • 1
    The accepted answer on the linked question is one example. You should still be careful about denial-of-service attacks, for example expressions like `9**9**9**9**9**9**9**9` which try to compute very large numbers and take impossibly long to complete, using up the CPU and memory, and hanging the program in the meantime. – kaya3 Dec 14 '19 at 21:49