David Chang
David Chang

Reputation: 53

String to Int conversion in python

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.

Upvotes: 0

Views: 329

Answers (2)

pradyunsg
pradyunsg

Reputation: 19406

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

Upvotes: 1

keyser
keyser

Reputation: 19189

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

Upvotes: 0

Related Questions