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 collections模块使用方法详解

Python collections模块使用方法详解

一、collections模块 1.函数namedtuple (1)作用:tuple类型,是一个可命名的tuple (2)格式:collections(列表名称,列表) (3)̴...

浅谈tensorflow中张量的提取值和赋值

浅谈tensorflow中张量的提取值和赋值

tf.gather和gather_nd从params中收集数值,tf.scatter_nd 和 tf.scatter_nd_update用updates更新某一张量。严格上说,tf.ga...

Python 类方法和实例方法(@classmethod),静态方法(@staticmethod)原理与用法分析

Python 类方法和实例方法(@classmethod),静态方法(@staticmethod)原理与用法分析

本文实例讲述了Python 类方法和实例方法(@classmethod),静态方法(@staticmethod)。分享给大家供大家参考,具体如下: demo.py(类方法,@classm...

Python实现的计算器功能示例

Python实现的计算器功能示例

本文实例讲述了Python实现的计算器功能。分享给大家供大家参考,具体如下: 源码: # -*- coding:utf-8 -*- #! python2 from tkinter i...

Python函数式编程

主要内容 1.函数基本语法及特性 2.参数与局部变 3.返回值 4.递归 5.名函数 6.函数式编程介绍 7.阶函数 8.内置函数 函数基本语法及特性 定义 数学函数定义:一般的,在一...