python模塊——re模塊(簡單的計算器功能實現_eval版)
阿新 • • 發佈:2018-07-03
earch 簡單的 group val class turn utf pla odin
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = "loki" # Usage: Make a Diy Calculator # example: # ‘1 - 2 * ((60-30 +(-40/5) * (9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))‘ import re RE_RULE = ‘\([^()]+\)‘ def arithmetical(temp): result = eval(temp) return result def main(arithmetic): step= 0 while 1: step += 1 result = re.search(RE_RULE, arithmetic) if result: # if exist ‘()‘ temp_ = result.group() calc_res = str(arithmetical(temp_)) arithmetic = re.sub(RE_RULE, calc_res, arithmetic) # replace source values print(arithmetic, "step: %s" % step) else: # if not ‘()‘ return arithmetical(arithmetic) if __name__ == ‘__main__‘:
print("result: %s" % (main(user_input)))
python模塊——re模塊(簡單的計算器功能實現_eval版)