Python 将字符串转换为浮点数
·
我们可以使用 float() 函数将字符串转换为 Python 中的浮点数。这是一个将对象转换为浮点数的内置函数。在内部float()函数调用指定对象 __float__() 函数。
Python 将字符串转换为浮点数
让我们看一个在 Python 中将字符串转换为浮点数的简单示例。
s = '10.5674'
f = float(s)
print(type(f))
print('Float Value =', f)
输出:
<class 'float'>
Float Value = 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}')
理想情况下,我们应该使用try-except块来捕获来自用户无效输入的异常。如果您不熟悉使用 f 前缀的字符串格式化,请阅读 Python](/community/tutorials/python-f-strings-literal-string-interpolation)中的[f-strings。
Python 将浮点数转换为字符串
我们可以使用 str() 函数轻松地将浮点数转换为字符串。有时我们想要连接浮点值时可能需要这样做。让我们看一个简单的例子。
f1 = 10.23
f2 = 20.34
f3 = 30.45
# using f-string from Python 3.6+, change to format() for older versions
print(f'Concatenation of {f1} and {f2} is {str(f1) + str(f2)}')
print(f'CSV from {f1}, {f2} and {f3}:\n{str(f1)},{str(f2)},{str(f3)}')
print(f'CSV from {f1}, {f2} and {f3}:\n{", ".join([str(f1),str(f2),str(f3)])}')
输出:
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
如果我们在上面的程序中不将float转换为字符串,join()函数会抛出异常。此外,我们将无法使用 + 运算符进行连接,因为它会添加浮点数。
您可以从我们的GitHub 存储库签出完整的 Python 脚本和更多 Python 示例。
参考:float() 官方文档
更多推荐
所有评论(0)