Python float() 函数用于将给定值转换为浮点数。浮点数是一种数字类型,表示带小数点的实数。它可以将各种类型的数据(例如数字字符串或整数)转换为浮点数。
请注意,提供的字符串应表示有效的数值;否则,将引发 ValueError 。
语法
以下是 Python float() 函数的语法 -
float(x)
参数
此函数接受一个数值或一个包含数字表示的字符串作为其参数。
返回值
此函数返回一个 float 对象。
示例 1以下是 Python float() 函数的示例。在这里,我们将整数 “42” 转换为浮点数 -
num = 42
float_num = float(num)
print('The float value obtained is:',float_num)
输出
以下是上述代码的输出 -
The float value obtained is: 42.0
示例 2
在这里,我们将字符串 “3.14” 转换为浮点数,得到浮点数 3.14 -
str_num = "3.14"
float_num = float(str_num)
print('The float value obtained is:',float_num)
输出
上述代码的输出如下 -
The float value obtained is: 3.14
示例 3
现在,我们使用 float() 函数将数学表达式的结果转换为浮点数。在这里,表达式 “10 / 3” 的结果被转换为浮点数 -
num1 = 10
num2 = 3
expression_result = float(num1 / num2)
print('The float value obtained is:',expression_result)
输出
获得的结果如下所示 -
The float value obtained is: 3.3333333333333335
示例 4
如果将包含非数字字符的字符串传递给 float() 函数,它将引发 ValueError。
在这里,我们将字符串 “25 bananas” 转换为浮点数 -
# Example with Error
mixed_string = "25 bananas"
number_part = float(mixed_string)
print(number_part)
输出
我们可以在下面的输出中看到,由于字符串包含非数字字符 (' apples'),导致转换过程中出现 ValueError -
Traceback (most recent call last):
File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in <module>
number_part = float(mixed_string)
ValueError: could not convert string to float: '25 bananas'
File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in <module>
number_part = float(mixed_string)
ValueError: could not convert string to float: '25 bananas'
示例 5
现在,我们处理一个同时包含数字和非数字字符的字符串。
首先,我们只从 “mixed_string” 中提取数字字符。我们使用列表推导式创建 “numeric_part” 变量,该推导式过滤掉非数字字符,从而生成仅包含数字 “25” 的字符串。最后,我们使用 float() 函数将此字符串转换为浮点数 -
# Example without Error
mixed_string = "25 bananas"
numeric_part = ''.join(char for char in mixed_string if char.isdigit())
number_part = int(numeric_part)
print('The integer value obtained is:',number_part)
输出
生成的结果如下 -
The float value obtained is: 25.0