from functools import reduce
def str2float(s):
# 移除小数点,把小数变为整数,记录下小数点的位置 n = 0 for x in s: n = n+1 if x=='.': s = s.replace('.', '') break DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} def fn(x,y): return x*10 + y def char2num(s): return DIGITS[s] #移除小数点后的整数 print(reduce(fn, map(char2num, s))) #加回小数点, 乘以 10**(len(s)-n+1) print(reduce(fn, map(char2num, s))/(10**(len(s)-n+1)))
str2float('21.65')
Sign in to make a reply
lemon9527
from functools import reduce
def str2float(s):
str2float('21.65')