0

Say I have a string '1+1', is it possible to convert it into a simple 'int' equation (1+1) to get 2? I've tried int('1+1') but I get ->ValueError: invalid literal for int() with base 10: '1+1'

Shoba
  • 11
  • `eval` is probably what you need to accomplish this. `print(eval('1+1'))`. Since `1+1` here is a string, int('1+1') cannot be parsed, int('1') + int('1') however, can – tidakdiinginkan May 02 '20 at 08:10
  • The answer would depend greatly on how much you want to accomplish. For example, are you looking to solve just sums? Or also subtractions, multiplications, etc? And how complex? If so, I’d update the question to specify that so you can obtain a more detailed answer :) – Pablo Alexis Domínguez Grau May 02 '20 at 08:12
  • 4
    Does this answer your question? [Evaluating a mathematical expression in a string](https://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string) – faressalem May 02 '20 at 08:13

2 Answers2

2

You'll need a parser (or e.g. ast.literal_eval(), eval() wich basically are or are built upon a parser):

string = '1+1'
result = eval(string)
print(result)
Jan
  • 42,290
  • 8
  • 54
  • 79
0

Use eval():

print(eval(‘1+1’))
2
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – codedge May 02 '20 at 12:02