python实现字符串转数字

from functools import reduce

def str2float(s):
	D={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
	i = s.index('.')
	s1 = s[:i]
	s2 = s[i+1:]
	def chr2num(ch):
		return D[ch]
	n1 = reduce(lambda x,y:x*10+y,map(chr2num,s1))
	n2 = reduce(lambda x,y:x*10+y,map(chr2num,s2))/(10**len(s2))
	return n1+n2

你可能感兴趣的:(python基础教程)