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使用metaclass实现Singleton模式的方法

本文实例讲述了Python使用metaclass实现Singleton模式的方法。分享给大家供大家参考。具体实现方法如下: class Singleton(type): def...

Anaconda2 5.2.0安装使用图文教程

Anaconda2 5.2.0安装使用图文教程

Anacond的介绍 Anaconda指的是一个开源的Python发行版本,其包含了conda、Python等180多个科学包及其依赖项。 因为包含了大量的科学包,Anacon...

Anaconda之conda常用命令介绍(安装、更新、删除)

Anaconda之conda常用命令介绍(安装、更新、删除)

anaconda用法: 查看已经安装的包: pip list 或者 conda list 安装和更新: pip install requests pip install request...

python使用 request 发送表单数据操作示例

python使用 request 发送表单数据操作示例

本文实例讲述了python使用 request 发送表单数据操作。分享给大家供大家参考,具体如下: # !/usr/bin/env python # -*- coding: utf-...

python 自定义对象的打印方法

在python中,如果不重写自定义对象的__str__方法,打印出来的对象是一串类似于<__main__.Bean object at 0x1007da470>的字符串。这当...