将字符串转换为算术运算

时间:2020-07-16 14:56:16

标签: python string integer

我有这个字符串:

x = "2x4, 2x5"

我想将其转换为以下操作:

x = (2 * 4) + (2 * 5)

所以最终结果将是18。

你有什么主意吗?如果该解决方案可以灵活地处理具有不同项目数的字符串(例如:“ 2x4、2x5、2x7”),那就太好了!

谢谢!

3 个答案:

答案 0 :(得分:1)

您可以使用operator.mul将这些数字相乘,然后使用sum将其相加,请尝试以下操作:

from operator import mul
x = "2x4, 2x5, 2x7"
print(sum(mul(*map(int, i.split('x'))) for i in x.split(', ')))

结果:

32

答案 1 :(得分:0)

split是你的朋友

def compute(equation):
    mults = equation.split(",")
    _sum = 0
    for mult in mults:
        terms = mult.split("x")
        products = 1
        for term in terms:
            products *= int(term)
        _sum += products
    return _sum

答案 2 :(得分:0)

使用评估

代码

def eval_str(s):
  ss = s.replace(',', '+').replace('x', '*')  # , -> + and 'x' -> *

  # disallow import and lamda functions (to make eval safe)
  if '__' in ss or 'import' in ss or 'lambda' in ss:
      return None  # disallow items that could make eval unsafe
  return eval(ss, {}, {})   # make eval safer by setting globals and locals to empty dictionary

用法

x = "2x4, 2x5"
print(eval_str(x))
# Output: 18

x = "2x4, 2x5, 2x7"
print(eval_str(x))
# Output: 32