from functools import reduce import logging def str2num(s): try: return int(s) except Exception as e: print(e) return float(s) def calc(exp): ss = exp.split('+') ns = map(str2num, ss) return reduce(lambda acc, x: acc + x, ns) def main(): L = ['100 + 200 + 345', '99 + 88 + 7s', '99 + 88 + 7.6'] for i in L: try: print(i, calc(i)) except Exception as e: logging.exception(e) main()
# 结果: 100 + 200 + 345 645 invalid literal for int() with base 10: ' 7s' invalid literal for int() with base 10: ' 7.6' 99 + 88 + 7.6 194.6
Sign in to make a reply
zjdddlll