如何在 Python 中将字符串转换为浮点数

介绍

在本文中,我们将使用Python的float()函数将字符串转换为浮动符串,我们还将使用Python的str()函数将浮动符串转换为浮动符串。

在使用它们进行计算和连接之前,必须正确转换数据类型,以防止运行时错误。

前提条件

为了完成本教程,您将需要:

本教程是用 Python 3.9.6 测试的。

使用float()函数

我们可以在Python中使用float()函数将字符串转换为浮动,这是一个内置的函数,用于将一个对象转换为浮点号。

例子

让我们看看如何在Python中将字符串转换为浮动的例子:

1input_1 = '10.5674'
2
3input_1 = float(input_1)
4
5print(type(input_1))
6print('Float Value =', input_1)

输出:

1<class 'float'>
2Float Value = 10.5674

字符串值为 '10,5674' 已转换为 '10,5674' 的浮动值。

为什么我们需要将字符串转换为浮动?

如果我们正在通过终端接收用户输入的浮点值或从文件中读取它,那么它们是字符串对象,我们必须明确地将它们转换为浮点,以便我们可以对它们执行必要的操作,如添加,倍增等。

1input_1 = input('Please enter first floating point value:\n')
2input_1 = float(input_1)
3
4input_2 = input('Please enter second floating point value:\n')
5input_2 = float(input_2)
6
7print(f'Sum of {input_1} and {input_2} is {input_1+input_2}')

<$>[注] 注: 如果您不熟悉使用 f前缀的字符串格式化,请阅读 f-strings in Python

让我们运行此代码,并为input_1input_2提供浮动值:

1Please enter first floating point value:
210.234
3Please enter second floating point value:
42.456
5Sum of 10.234 and 2.456 is 12.69

结果的102342456的总和为12.69

理想情况下,我们应该使用一个试用除外块来捕捉例外,如果用户输入无效。

使用「str()」函数

我们还可以使用 str() 函数将 float 转换为字符串,这可能需要在我们想要连接 float 值的情况下。

例子

让我们来看看一个例子:

1input_1 = 10.23
2input_2 = 20.34
3input_3 = 30.45
4
5# using f-string from Python 3.6+, change to format() for older versions
6print(f'Concatenation of {input_1} and {input_2} is {str(input_1) + str(input_2)}')
7print(f'CSV from {input_1}, {input_2} and {input_3}:\n{str(input_1)},{str(input_2)},{str(input_3)}')
8print(f'CSV from {input_1}, {input_2} and {input_3}:\n{", ".join([str(input_1),str(input_2),str(input_3)])}')

让我们运行这个代码:

1Concatenation of 10.23 and 20.34 is 10.2320.34
2CSV from 10.23, 20.34 and 30.45:
310.23,20.34,30.45
4CSV from 10.23, 20.34 and 30.45:
510.23, 20.34, 30.45

连接10.2320.34会产生字符串10.2320.34

如果我们在上面的程序中不将 float 转换为字符串,则 join() 函数将引发例外;此外,我们将无法使用 + 操作员来连接,因为它会添加浮点数。

结论

您可以从我们的 GitHub 存储库查看完整的 Python 脚本和更多 Python 示例。

** 参考:**

Published At
Categories with 技术
Tagged with
comments powered by Disqus