def convert_to_float(frac_str): try: return float(frac_str) except ValueError: num, denom = frac_str.split('/') try: leading, num = num.split(' ') whole = float(leading) except ValueError: whole = 0 frac = float(num) / float(denom) return whole - frac if whole < 0 else whole + fracprint convert_to_float('3') # 3.0print convert_to_float('3/2') # 1.5print convert_to_float('1 1/2') # 1.5print convert_to_float('-1 1/2') # -1.5
http://ideone.com/ItifKv
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)