0

I want to convert a string such as '246 + 34' into an integer such as 246 + 34. How can I do this? My goal is to print the sum of the equation in the string.

I have tried int('246 + 34'), but I get the error

ValueError: invalid literal for int() with base 10: '246+34'

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
DineshYes
  • 1
  • 1
  • One way that I'm pretty sure will work is to parse the string into a symbolic expression and evaluate that, via Sympy (https://sympy.org). There may be other ways to do it. – Robert Dodier May 16 '21 at 23:33

1 Answers1

0

Two options that I know of would to use eval(equation) or

string = '246 + 34'.split()
equation = None

if string[1] == '+': equation = int(string[0]) + int(string[2])
if string[1] == '-': equation = int(string[0]) - int(string[2])
if string[1] == '/': equation = int(string[0]) / int(string[2])
if string[1] == '*': equation = int(string[0]) * int(string[2])

Which splits the equation by spaces and separates numbers and operators.

Buddy Bob
  • 5,829
  • 1
  • 13
  • 44