如何使字符串计算命令?

时间:2014-01-22 14:09:30

标签: python string

有没有办法通过替换将"1 plus 3 minus 4"转换为"1 + 3 - 4"来计算它?

3 个答案:

答案 0 :(得分:4)

是的,您可以使用str.replace将这些字词替换为符号,然后使用eval来评估计算:

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 :(得分:2)

一种方法是使用eval,但应该使用正确的验证。

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)

答案 2 :(得分:1)

如果输入来自已知来源,则在使用适当的运算符替换evalplus后,对字符串使用minus

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