def count(arg): #计算字符串 result = eval(arg) return result import re origin = "1 - 2 * ((60 - 20 +(-40.5/5) * (9 - 2*5/3 + 2*10 + 10*8/144 )) - (-4*3)/(16 - 3*2))" while True: n = re.split("(([^()]+))", origin, 1) #对origin进行分割,从最里面的括号开始,逐步进行 if len(n) == 3: before = n[0] content = n[1] #正则分割的那段调用str的eval计算 after = n[2] num = count(content) new_str = str(num) origin = before + new_str + after #计算的结果重新合并成一个新的字符串 else: #当不含有括号,直接调用eval方法 result = count(origin) print(result) break