python:字符串转浮点数 str2float('123.4567)

最近在学习廖雪峰老师的python教程 借鉴各路大神的思路进行整理记录,以供参考

from functools import reduce #导入reduce 函数

def str2float(s):
    n=s.index('.')
    s1,s2=list(map(int,s[:n])),list(map(int,s[n+1:]))
    return reduce(lambda x,y:x*10+y,s1+s2)/(10**(len(s)-n-1))                 
print('str2float(\'123.4567\')=',str2float('123.4567'))

猜你喜欢

转载自blog.csdn.net/leeningzzu/article/details/80405006
今日推荐