Python字符串转换成浮点数函数分享

yipeiwu_com5年前Python基础

利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456

from functools import reduce
 
def str2float(s):
  return reduce(lambda x,y:x+int2dec(y),map(str2int,s.split('.')))
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 str2int(s):
  return reduce(lambda x,y:x*10+y,map(char2num,s))
def intLen(i):
  return len('%d'%i)
def int2dec(i):
  return i/(10**intLen(i))
   
print(str2float('123.456'))

以上就是本代码的全部内容了,希望对大家学习Python能够有所帮助。

相关文章

python通过加号运算符操作列表的方法

本文实例讲述了python通过加号运算符操作列表的方法。分享给大家供大家参考。具体如下: li = ['a', 'b', 'mpilgrim'] li = li + ['exampl...

详解Python中字符串前“b”,“r”,“u”,“f”的作用

1、字符串前加 u 例:u"我是含有中文字符组成的字符串。" 作用: 后面字符串以 Unicode 格式 进行编码,一般用在中文字符串前面,防止因为源码储存格式问题,导致再次使用时出现乱...

Python enumerate遍历数组示例应用

    其他语言中,比如C#,我们通常遍历数组是的方法是:for (int i = 0; i <&nbs...

python encode和decode的妙用

>>> "hello".encode("hex") '68656c6c6f' 相应的还可以 >>> '68656c6c6f'.decode("hex"...

Python之循环结构

while循环结构 格式: while 表达式: 语句块 执行流程:当程序执行到while语句时,首先判断表达式的真假。若表达式的值为真,则执行缩进的语句块,之后返回表达式继续...