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
Saphire
1,9602 gold badges18 silver badges38 bronze badges
3 Answers 3
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
jonrsharpe
123k31 gold badges278 silver badges489 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Ashwini Chaudhary
ast.literal_eval can only be used with list, tuples, string etc, not with expressions.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
Sudipta
4,9712 gold badges31 silver badges43 bronze badges
Comments
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
Ashwini Chaudhary
252k60 gold badges479 silver badges520 bronze badges
Comments
lang-py
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.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 allowing0123456789+-in the strings you try to evaluate.