Python将string转换到float的实例方法

yipeiwu_com6年前Python基础

Python 如何转换string到float?简单几步,让你轻松解决。

打开软件,新建python项目,如图所示

右键菜单中创建.py文件,如图所示

步骤中文件输入代码如下:

def string_to_float(str):

return float(str)

if __name__ == '__main__':

str = '3.1415926'

res = string_to_float(str)

print(res + 1)

空白后,右键菜单中选择【Run 'test'

查看运行结果如下图所示

需要转换string到float,直接调用图中的函数即可。

知识点扩展

python str转换成float

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

fromfunctoolsimportreduce
 
defstr2float(s):
 returnreduce(lambdax,y:x+int2dec(y),map(str2int,s.split('.')))
defchar2num(s):
 return{'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}[s]
defstr2int(s):
 returnreduce(lambdax,y:x*10+y,map(char2num,s))
defintLen(i):
 returnlen('%d'%i)
defint2dec(i):
 returni/(10**intLen(i))
  
print(str2float('123.456'))

以上就是本次关于Python如何转换string到float全部知识点,感谢大家对【听图阁-专注于Python设计】的支持。

相关文章

python pillow模块使用方法详解

pillow Pillow是PIL的一个派生分支,但如今已经发展成为比PIL本身更具活力的图像处理库。pillow可以说已经取代了PIL,将其封装成python的库(pip即可安装),...

python读取dicom图像示例(SimpleITK和dicom包实现)

1. 用SimpleITK读取dicom序列: import SimpleITK as sitk import numpy as np img_path='F:\\dataset\\...

django如何实现视图重定向

当请求访问到某个视图时,我们想让它重定向到其他页面,应该怎么做呢? 1.HttpResponseRedirect 需求:当我们访问127.0.0.1/my_redirect时跳到127...

python的turtle库使用详解

python的turtle库使用详解

python中的turtle库是3.6版本中新推出的绘图工具库,那么如何使用呢?下面小编给大家分享一下。 首先打开pycharm软件,右键单击选择新建一个python file 接下来...

使用Python的Supervisor进行进程监控以及自动启动

使用Python的Supervisor进行进程监控以及自动启动

做服务器端开发的同学应该都对进程监控不会陌生,最近恰好要更换 uwsgi 为 gunicorn,而gunicorn又恰好有这么一章讲进程监控,所以多研究了下。 结合之前在腾讯工作的经验,...