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
  • 112,593
  • 23
  • 157
  • 280
Oliver Brace
  • 323
  • 2
  • 17

2 Answers2

0

You can use the eval function.

    eval("1 + 1")
Bruno L
  • 689
  • 4
  • 9
0

You could use ast.literal_eval:

import ast

line = "1+1"
print(ast.literal_eval(line))
# 2
Austin
  • 25,142
  • 4
  • 21
  • 46