-1

I have a string of calculations which I parsed to get first operand, second operand and symbol used in calculation.

op01, sym0, op02 = "1", "+", "5"

Now I want to perform calculation on it but could not figure out how? I want

op01 sym0 op02

which should become:

1 + 5

and give the result:

6
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

1 Answers1

1

The operator module provides functions that correspond to each of the operators, but there is no predefined mapping of the symbols to their intended implementation. You'll have to define that yourself.

import operator

ops = {"+": operator.add}

op01, sym0, op02 = "1", "+", "5"

print(ops[sym0](int(op01), int(op02)))  # Outputs 6
chepner
  • 497,756
  • 71
  • 530
  • 681