0

I am trying to create a short program to do a task. Unfortunately I keep getting an error. The problem boils down to the following.

If I try to run:

line = "1+1"
int(line)

I would like it to return

2

However I get the following error:

invalid literal for int() with base 10: '1+1'

From looking online this is due to the fact that Python cannot recognize the fact that I have used a non-number. However without some rework I can't get around this.

I was hoping that there is a straight forward method for solving this. I have tried using float but that has the same problem.

martineau
  • 119,623
  • 25
  • 170
  • 301
Oliver Brace
  • 393
  • 1
  • 4
  • 21

2 Answers2

1

You can use the eval function.

    eval("1 + 1")
Bruno L
  • 839
  • 5
  • 9
0

You could use ast.literal_eval:

import ast

line = "1+1"
print(ast.literal_eval(line))
# 2
Austin
  • 25,759
  • 4
  • 25
  • 48