0

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.

3
  • ummm, converting to postfix then evaluating?... Commented May 4, 2013 at 18:15
  • eval is actually a function that does exactly this! Commented May 4, 2013 at 18:17
  • oh I didn't even know that existed, thank you! It works now. Commented May 4, 2013 at 18:17

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

If the input comes from the user you should not use eval
Everyone knows that eval is not safe to use if you get user input, because it is executing arbitrary code. He should at least sanitize the input if he uses it.
(@Keyser) I know your answer works, not arguing that, just don't want to teach someone who might be a beginner bad habits
Yeah, probably ast.literal_eval would be a safer choice, since it only considers a small subset of Python's syntax to be valid.
whether you should use 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.