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中datetime模块中strftime/strptime函数的使用

python中datetime模块中strftime/strptime函数的使用

Python 的datetime模块 其实就是date和time 模块的结合,常见的属性方法都比较常用 比如: datetime.day,datetime.month,datet...

Python实现FTP上传文件或文件夹实例(递归)

本文实例讲述了Python实现FTP上传文件或文件夹实例。分享给大家供大家参考。具体如下: import sys import os import json from ftp...

用Python抢火车票的简单小程序实现解析

利用Python制作自动抢火车票小程序,过年再也不要担心没票了! 前言 每次过年很多人都会因为抢不到火车票而回不了家,所以小编利用Python写了一个自动抢火车票的工具,希望大家能抢到...

python自定义线程池控制线程数量的示例

1.自定义线程池 import threading import Queue import time queue = Queue.Queue() def put_data...

Python脚本在Appium库上对移动应用实现自动化测试

 采用Appium进行自动化的功能性测试最酷的一点是,你可以使用具有最适合你的测试工具的任何一门语言来写你的测试代码。大家选择最多的一个测试编程语言就是Python。 使用Ap...