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中init方法和随机数方法

1、__init__方法的使用 2、random方法的使用 在python中,有一些方法是特殊的,是以两个下划线开始,两个下划线结束,定义类,最常用的方法就是__init__()方法,这...

python和opencv实现抠图

本文实例为大家分享了python实现抠图的具体代码,供大家参考,具体内容如下 其中使用了opencv中的grabcut方法 直接上代码 # encoding:utf-8 # 图像提取...

python中map()与zip()操作方法

对于map()它的原型是:map(function,sequence),就是对序列sequence中每个元素都执行函数function操作。 比如之前的a,b,c = map(int,r...

初探利用Python进行图文识别(OCR)

初探利用Python进行图文识别(OCR)

话说什么是OCR????? 简介 OCR技术是光学字符识别的缩写(Optical Character Recognition),是通过扫描等光学输入方式将各种票据、报刊、书籍、文稿及其...

pytorch 状态字典:state_dict使用详解

pytorch 中的 state_dict 是一个简单的python的字典对象,将每一层与它的对应参数建立映射关系.(如model的每一层的weights及偏置等等) (注意,只有那些参...