-1

For example if i have:

x = '12'
print(int(x))

would turn x into an integer from a string.

What if I have:

x = '1+2'

And I want 3 as my output, how would I go about it since + cannot be converted into an int directly?

salmanwahed
  • 9,450
  • 7
  • 32
  • 55
F. Yam
  • 1

3 Answers3

3

Use literal_eval which is much more safer than using eval. literal_eval safely evaluates an expression node or a string containing a python expression.

import ast
x = ast.literal_eval('1+2')
salmanwahed
  • 9,450
  • 7
  • 32
  • 55
0

You could use the eval function to accomplish this; however, it should be noted that allowing unsanitized input into the eval function can pose a significant security risk. Here's an example:

x = '1 + 2'
print(eval(x))
Acontz
  • 471
  • 4
  • 11
-1

Here you can use eval.
The usage is eval(expression[, globals[, locals]]).
Therefore eval('1+2') 3

Lunar_one
  • 337
  • 3
  • 4