Is there a way to convert "1 plus 3 minus 4" to "1 + 3 - 4" through replacing, to calculate it as such?
3 Answers
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
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)
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.