Discuss / Python / 一开始不知道用str.find函数,写起来超级费劲。。。。

一开始不知道用str.find函数,写起来超级费劲。。。。

Topic source

taogebuaa

#1 Created at ... [Delete] [Delete and Lock User]
from functools import reduce

def char2num(s):
        return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
def fn1(x,y):
    return 10*x+y
def fn2(x,y):
    return 0.1*x+y


def str2float(s):
    point=s.find('.')
    s1=s[0:point]
    s2=s[point+1::]
    num=reduce(fn1, map(char2num,s1))+reduce(fn2,map(char2num,s2[::-1]))/10
    return num
print('str2float(\'123.456\') =', str2float('123.456'))

  • 1

Reply