简介
在这篇文章中,我们将使用Python的float() 函数将字符串转换为浮点数。我们还将使用Python的str() 函数将浮点数转换为字符串。
在使用数据类型进行计算和连接之前,正确地转换数据类型是很重要的,以防止运行时出错。
使用float() 函数
我们可以在Python中使用float() 函数将字符串转换为浮点数。这是一个内置函数,用于将一个对象转换为浮点数。在内部,float() 函数调用指定的对象__float__() 函数。
例子
让我们看一个在Python中把字符串转换为浮点数的例子。
input_1 = '10.5674'
input_1 = float(input_1)
print(type(input_1))
print('Float Value =', input_1)
输出
<class 'float'>
Float Value = 10.5674
字符串的值'10.5674' 已经被转换为浮点数10.5674 。
为什么我们需要将字符串转换为浮点数?
如果我们通过终端接收来自用户输入的浮动值或从文件中读取,那么它们就是字符串对象。我们必须明确地将它们转换为浮点数,这样我们才能对它们进行必要的操作,如加法、乘法等。
input_1 = input('Please enter first floating point value:\n')
input_1 = float(input_1)
input_2 = input('Please enter second floating point value:\n')
input_2 = float(input_2)
print(f'Sum of {input_1} and {input_2} is {input_1+input_2}')
让我们运行这段代码,为input_1 和input_2 提供浮点数。
Please enter first floating point value:
10.234
Please enter second floating point value:
2.456
Sum of 10.234 and 2.456 is 12.69
10.234 和2.456 的结果之和是12.69 。
理想情况下,我们应该使用一个try-except 块来捕捉用户无效输入时的异常。
使用str() 函数
我们还可以使用str() 函数将浮点数转换为字符串。在我们想要连接浮点数的情况下,可能需要这样做。
例子
让我们看一个例子。
input_1 = 10.23
input_2 = 20.34
input_3 = 30.45
# using f-string from Python 3.6+, change to format() for older versions
print(f'Concatenation of {input_1} and {input_2} is {str(input_1) + str(input_2)}')
print(f'CSV from {input_1}, {input_2} and {input_3}:\n{str(input_1)},{str(input_2)},{str(input_3)}')
print(f'CSV from {input_1}, {input_2} and {input_3}:\n{", ".join([str(input_1),str(input_2),str(input_3)])}')
让我们运行这段代码。
Concatenation of 10.23 and 20.34 is 10.2320.34
CSV from 10.23, 20.34 and 30.45:
10.23,20.34,30.45
CSV from 10.23, 20.34 and 30.45:
10.23, 20.34, 30.45
将10.23 和20.34 连接起来,产生字符串'10.2320.34' 。这段代码还产生了两个版本的逗号分隔的值(CSV)。
如果我们在上面的程序中不把浮点数转换为字符串,join() 函数将抛出一个异常。此外,我们将无法使用+ 操作符进行连接,因为它将增加浮点数。
总结
你可以从我们的[GitHub资源库]中查看完整的Python脚本和更多的Python例子。