1

Is there a way to convert "1 plus 3 minus 4" to "1 + 3 - 4" through replacing, to calculate it as such?

asked Jan 22, 2014 at 14:09
3
  • You'd probably have to hard code it to check for words like "plus" and "minus" and replace them with the appropriate symbol, then use eval() -- I think Python has this. Commented Jan 22, 2014 at 14:11
  • 1
    If you're using eval(), please validate (as usual, but this case in particular) the input. I would actually prefer some kind if library that parses the string as an expression, so that injection isn't possible. Commented Jan 22, 2014 at 14:16
  • Don't use eval() for this unless you don't care about somebody deleting your hard drive with your cute calculator program. It's also dead simple to write a little stack based state machine to calculate mathematical expressions like this, which is considerably safer and could probably even be faster. If you still prefer using eval, with limited input like this you could actually be safe by using a character-based whitelist; e.g. only allowing 0123456789+- in the strings you try to evaluate. Commented Jan 22, 2014 at 15:10

3 Answers 3

4

Yes, you can use str.replace to replace the words with the symbols, then eval to evaluate the calculation:

def evaluate(s):
 replacements = {'plus': '+', 'minus': '-'} # define symbols to replace
 for word in replacements:
 s = s.replace(word, replacements[word]) # replace them
 return eval(s) # evaluate calculation
>>> s = "1 plus 3 minus 4"
>>> evaluate(s)
0
answered Jan 22, 2014 at 14:13
Sign up to request clarification or add additional context in comments.

1 Comment

ast.literal_eval can only be used with list, tuples, string etc, not with expressions.
2

One way is to use eval, but it should be used with proper validations.

abc = "1 plus 3 minus 4"
operatorMap = {"plus":"+","minus":"-"}
evalString = ""
for value in abc.split():
 try:
 val = str(int(value))
 except:
 try:
 val = operatorMap[value]
 except:
 print "Error!!"
 break
 evalString += val
print eval(evalString)
answered Jan 22, 2014 at 14:23

Comments

1

If the input is coming from a known source, then use eval on the string after replacing plus, minus with appropriate operators.

>>> s = "1 plus 3 minus 4"
>>> d = {'plus':'+', 'minus':'-'}
>>> eval(' '.join(d.get(x, x) for x in s.split()))
0
answered Jan 22, 2014 at 14:13

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.