如何在符号前后输入的算术运算中组合数字,例如“+”或“-”

How to combine numbers inside an arithmetic operation input before and after the sign for example "+" or "-"

如果这个问题已经得到解答,我深表歉意,但我搜索了这个但找不到答案。也许我以一种奇怪的方式写了这个问题,但我是新来的,所以我很抱歉。 我的代码有很多问题,我认为它非常低效,因为如果 a + b 的输入例如是 -25 + 2 那么 a 将只读取 operation[1],这将是 2,当我 运行 它时,它不会给我想要的答案。 长话短说,有没有办法在符号前输入一行将所有数字组合在一起的代码? 例如 a = (-) 之前的所有数字,b = 符号 (-) 之后的所有数字。 这是我正在尝试编写的代码示例:

operation = input('Enter an arithemtic operation: ')
print(operation)
operation = operation.replace(" ", "")
if len(operation) == 3:
    a = int(operation[0])
    b = int(operation[2])
    sign2 = operation[1]
    if(sign2 == '+'):
        sum = a + b
        print(sum)
    elif(sign2 == '-'):
        sum = a - b
        print(sum)
    elif(sign2 == '*'):
        sum = a * b
        print(sum)
    elif(sign2 == '/'):
        sum = a / b
        print(round(sum, 3))

elif len(operation) == 4:
    a = int(operation[1]) * -1
    b = int(operation[3])
    sign1 = operation[0]
    sign2 = operation[2]
    if(sign2 == '+'):
        sum = a + b
        print(sum)
    elif(sign2 == '-'):
        sum = a - b
        print(sum)
    elif(sign2 == '*'):
        sum =  a * b
        print(sum)
    elif(sign2 == '/'):
        sum = a / b
        print(round(sum, 3))

    


else:
    print('input invalid')

你可以使用 re 库中的正则表达式 (Regex),它有点复杂,但如果你学习了基础知识,它将对你有很大帮助。检查下面我的建议

import re

def foo():
    operation = input("Enter Operation: ")
    match = re.findall(r"([+-]\d+)\b\s*([+-])\s*(\d+)", operation) # This line finds the three components of the equation/operation (LHS, sign & RHS) and excludes any spaces in-between
    lft = int(match[0][0])
    rght = int(match[0][-1])
    sign = match[0][1]
    if sign == "+":
        return lft + rght
    elif sign == "-":
        return lft - rght
    else:
        return False

一般来说,您应该会找到很多与正则表达式相关的帮助,但值得学习一下。 Sentdex 对此有很好的 tutorial

抱歉,如果这是错误的,因为我可能没有理解正确的问题,但是你不能只使用 eval 来获取算术运算的值吗?

example_input = "1 + 2 * 3"

print(eval(example_input))

## OUTPUT:
# 7

只要在 example_input 中输入的表达式是有效的 python 表达式,这就会起作用。