If I have a string "2+3", is there anyway to convert it to an integer so it comes out as 5?
I tried this:
string = 2+3
answer = int(string)
But I get an error:
ValueError: invalid literal for int() with base 10: '2+3'
I'm trying to take a fully parenthesized equation and use stacks to answer it.
ex. Equation = ((2+3) - (4*1))
I tried taking the equation as an input, but python just solves it on its own. So to avoid that problem, I took the equation as a raw_input.
2 Answers 2
There is one way, eval function..
>>> x = raw_input()
2 + 6
>>> x
'2 + 6'
>>> eval(x)
8
But be sure to verify that the input only has numbers,and symbols.
>>> def verify(x):
for i in x:
if i not in '1234567890.+-/*%( )':
return False
return True
>>> x = raw_input()
2 + 6
>>> x
'2 + 6'
>>> if verify(x):
print eval(x)
8
ast.literal_eval doesn't work:
>>> ast.literal_eval('2+3')
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
ast.literal_eval('2+3')
File "C:\Python2.7 For Chintoo\lib\ast.py", line 80, in literal_eval
return _convert(node_or_string)
File "C:\Python2.7 For Chintoo\lib\ast.py", line 79, in _convert
raise ValueError('malformed string')
ValueError: malformed string
Comments
Use eval (and remember to sanitize your input. More on this if you read the docs):
>>> eval('2+3')
5
It even supports variables:
>>> x = 1
>>> eval('x+1')
2
5 Comments
ast.literal_eval would be a safer choice, since it only considers a small subset of Python's syntax to be valid.eval() with user input depends on if you trust the user. Often, you do; but still need to protect the user from accidentally executing code on their behalf from a third party your user does not trust.
evalis actually a function that does exactly this!