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设计】的支持。

相关文章

Centos7 下安装最新的python3.8

Python 3.8是Python语言的最新版本,它适合用于编写脚本、自动化以及机器学习和Web开发等各种任务。现在Python 3.8已经进入官方的beta阶段,这个版本带来了许多语法...

python读取文本中的坐标方法

利用python读取文本文件很方便,用到了string模块,下面用一个小例子演示读取文本中的坐标信息。 import string x , y , z = [] , [] ,[]...

Python简单计算文件MD5值的方法示例

本文实例讲述了Python简单计算文件MD5值的方法。分享给大家供大家参考,具体如下: 一 代码 import sys import hashlib import os.path f...

深入浅析Python获取对象信息的函数type()、isinstance()、dir()

深入浅析Python获取对象信息的函数type()、isinstance()、dir()

type()函数: 使用type()函数可以判断对象的类型,如果一个变量指向了函数或类,也可以用type判断。 如: class Student(object): name = '...

pytorch 自定义参数不更新方式

nn.Module中定义参数:不需要加cuda,可以求导,反向传播 class BiFPN(nn.Module): def __init__(self, fpn_sizes):...