0

I need to do something like this :

expresii.txt

3+5
2-3

iesire.txt

3+5=8
2-3=-1

I converted "expresii.txt" in a list, but I don't know how to read an operator and make the operation.

f = open("expresii.txt", "r")
with open("iesire.txt",'w',encoding = 'utf-8') as f:
   List = open("expresii.txt").readlines()
List = [x.strip() for x in List]
print(List)
  • you may need to use `eval("3+5")` to calculate result. OR you would have to write own parser - from scratch (using ie. `if text[1] == '+': ...`) or using tools like ie. [ply](https://github.com/dabeaz/ply), [sly](https://github.com/dabeaz/sly) – furas Apr 03 '22 at 12:11

1 Answers1

1

The simplest option would be go with eval, however it's not safe. On the other edge is to program whole parser by yourself, which includes checking the type of the input (weather it's number or operator), transforming them into python operators, checking the order of execution etc... Which might be a lot of work.

Talking about some safer and easier solutions these references might be helpful:

numexpr lib Safely evaluate simple string equation

ast, asteval, Pyparsing Evaluating a mathematical expression in a string

Aidas
  • 114
  • 4