python字符串转换为float类型

时间:2020-02-23 14:43:25  来源:igfitidea点击:

在本教程中,我们将看到如何将字符串转换为float数据类型。

我们可以简单地使用float()函数来将字符串转换为float数据类型。
让我们看一个简单的例子。

str="22.4543232"
f=float(str)
print("Type of f:",type(f))
print(f)

输出:

Type of f: 
22.4543232

如果字符串无法转换为float,会发生什么

如果不能转换字符串浮动,那么它将引发ValueError。
让我们通过示例来理解。

str="abc"
f=float(str)
print(f)

输出:

—————————————————————————
ValueError                                Traceback (most recent call last)
 in ()
      1 str="abc"
—-> 2 f=float(str)
      3 print(f)
ValueError: could not convert string to float: 'abc'
valueError:无法将字符串转换为float:'abc'