【问题标题】:Is there way to convert string "1+2-3" to a result 0 [closed]有没有办法将字符串“1 + 2-3”转换为结果0 [关闭]
【发布时间】:2020-04-08 22:10:43
【问题描述】:

我有一个字符串'1plus2minus3',我可以将它转换成字符串'1+2-3'

有没有办法通过将此str() 转换为int() 来计算结果?

【问题讨论】:

  • 如果字符串来自用户输入,请不要使用eval,我肯定会在答案中建议

标签: python python-3.x string algorithm integer


【解决方案1】:

eval() 已经有了答案,但这里有另一个答案,使用re 模块,更安全:

s = '1+2-3'

import re

result = sum(map(int, re.findall(r'[+-]?\d+', s)))
print(result)

打印:

0

【讨论】:

    【解决方案2】:

    您可以执行以下步骤:

    1. 将字符串plus 替换为+,将minus 替换为-
    2. 使用eval()eval('1+2-3') 将导致 0

    【讨论】:

    • 谢谢!那是我正在寻找的
    【解决方案3】:

    快速解决办法是

    eval('1+2-3') == 0
    

    【讨论】:

      猜你喜欢
      • 2023-01-30
      • 1970-01-01
      • 2011-01-10
      • 2013-08-13
      • 2011-02-11
      • 1970-01-01
      • 1970-01-01
      • 2017-07-15
      • 1970-01-01
      相关资源
      最近更新 更多