Python 中的 float()

pythonserver side programmingprogramming更新于 2025/9/22 13:32:17

Float 方法是 Python 标准库的一部分,它将数字或包含数字的字符串转换为浮点数据类型。将字符串转换为浮点时,有以下规则。

  • 字符串中必须只有数字。

  • 数字之间也可以使用数学运算符。

  • 字符串可以表示 NaN 或 inf

  • 开头和结尾的空格始终被忽略。

示例

以下程序显示了应用浮点函数时如何返回不同的值。

n = 89
print(type(n))
f = float(n)
print(type(f))
print("input",7," with float function becomes ",float(7))
print("input",-21.6," with float function becomes ",float(-21.6))
print("input NaN, with float function becomes ",float("NaN"))
print("input InF, with float function becomes ",float("InF"))

输出

运行上述代码得到以下结果 −

<class 'int'>
<class 'float'>
input 7 with float function becomes 7.0
input -21.6 with float function becomes -21.6
input NaN, with float function becomes nan
input InF, with float function becomes inf

传递没有任何数值的流会引发错误。

示例

print("input Tutorials, with float function becomes ",float("Tutorials"))

输出

运行上述代码得到以下结果 −

Traceback (most recent call last):
   File "C:/xxx.py", line 18, in
      print("input Tutorials, with float function becomes ",float("Tutorials"))
ValueError: could not convert string to float: 'Tutorials'

相关文章


有用资源