Python将字符串转换为浮点数
时间:2020-02-23 14:42:33 来源:igfitidea点击:
我们可以使用float()函数将字符串转换为float在Python中。
这是一个内置功能,可将对象转换为浮点数。
内部float()函数调用指定的对象__float __()
函数。
Python将字符串转换为浮点数
让我们看一个简单的示例,将字符串转换为在Python中为float。
s = '10.5674' f = float(s) print(type(f)) print('Float Value =', f)
输出:
<class 'float'> Float Value = 10.5674
为什么我们需要将字符串转换为float?
如果我们通过终端通过用户输入获取浮点值或者从文件中读取浮点值,则它们是字符串对象。
因此,我们必须将它们显式转换为float,以便对其执行必要的操作,例如加法,乘法等。
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中的f字符串。
Python将float转换为String
我们可以使用str()函数轻松地将float转换为字符串。
有时在我们要连接浮点值的地方可能需要这样做。
让我们看一个简单的例子。
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()函数将引发异常。
另外,我们将无法使用+运算符进行连接,因为它将添加浮点数。