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?
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?
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')
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))
Here you can use eval.
The usage is eval(expression[, globals[, locals]]).
Therefore
eval('1+2')
3