0

How does one convert a string list such as:

string = ["+5*-5"]

into something such as

string = [+5*-5]

so I can evaluate each of this type of expression mathematically without using libraries, import, eval or similar

I've tried the usual type converts and this does not work unfortunately.

Many thanks

yousurf
  • 1
  • 1
  • So, your desired result is `[-25]`? – Klaus D. Nov 23 '19 at 12:40
  • you can try using the [ast](https://docs.python.org/3/library/ast.html) module – Thomas Nov 23 '19 at 12:40
  • Write a parser for arithmetical expressions. If you want to avoid libraries, this is a nontrivial task (depending on the anticipated complexity of the expressions). – John Coleman Nov 23 '19 at 12:42
  • https://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string – pask Nov 23 '19 at 12:43
  • @JohnColeman Agreed re: `eval` being evil, and I did miss that bit of the question... – larsks Nov 23 '19 at 12:45
  • What about checking whether a string only contains numbers (digits, ...) and operators before using eval? – coproc Nov 23 '19 at 13:00
  • what's the problem in using eval ? – Vicrobot Nov 23 '19 at 13:01
  • @Vicrobot Often there is no danger at all in using `eval`, but if you run `eval` on untrusted data, it is a major security hole. If you write server-side code that passes an unvetted string to `eval` (e.g. under the assumption that the user has entered an arithmetical expression), and attacker could trick your code into evaluating something devious. The real problem in a use-case like OP's is that it encourages bad habits which *might* lead to the programmer reaching for `eval` in a context in which it is genuinely dangerous. – John Coleman Nov 23 '19 at 14:27

1 Answers1

0

A fast and safe way is to use numexpr as follows:

import numexpr

string = ["+5*-5"]
for s in string:                     # Loop over all elements in your list
    print(numexpr.evaluate(string))  # Evaluate and print result
jkazan
  • 1,149
  • 12
  • 29