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模拟自动存取款机的查询、存取款、修改密码等操作

1.工作流程 2.模拟自动存取款机的操作 代码如下: import msvcrt, sys, os #定义用星号隐藏密码输入的函数 def psw_input(): li =...

Django应用程序入口WSGIHandler源码解析

前言 WSGI 有三个部分, 分别为服务器(server), 应用程序(application) 和中间件(middleware). 已经知道, 服务器方面会调用应用程序来处理请求, 在...

python之pyqt5通过按钮改变Label的背景颜色方法

python之pyqt5通过按钮改变Label的背景颜色方法

使用setStyleSheet方法修改得到自己想要的字体,大小,颜色 self.lab = QLabel("标签字体大小颜色", self) self.lab.setGeometry...

python线程、进程和协程详解

引言 解释器环境:python3.5.1 我们都知道python网络编程的两大必学模块socket和socketserver,其中的socketserver是一个支持IO多路复用和多...

python实现dnspod自动更新dns解析的方法

复制代码 代码如下:def ddns():"""用当前ip更新ddns"""headers = {"Content-type": "application/x-www-form-urle...