迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Python 中错误 ValueError: Invalid Literal for Float()

作者:迹忆客 最近更新:2023/05/16 浏览次数:

当您传递 float() 函数不支持的无法识别的参数时,Python 编译器将出现错误,例如 ValueError: invalid literal for float() 。 当您将字符串值作为参数传递给 float() 函数时,python 编译器会出现此 Python 2x 版本 ValueError: invalid literal for float() 和 Python 3x 版本 ValueError: could not convert string to float

Python 中 ValueError: invalid literal for float()

float() 函数无法将字符串类型转换为浮点数。 相反,它会抛出一个 ValueError,它可能会因您的 Python 版本而异。

让我们看一个 Python 2 和 Python 3 的例子。

代码 - Python 2:

# python 2.7
import sys

print("The Current version of Python:", sys.version)

x = '123xyx'
y = float(x)
print(y)

输出:

The current version of Python: 2.7.18
ValueError: invalid literal for float(): 123xyx

代码 - Python 3:

# python 3.7
import sys

print("The Current version of Python:", sys.version)

x = '123xyx'
y = float(x)
print(y)

输出:

The current version of Python: 3.7.4
ValueError: could not convert string to float: '123xyx'

我们在 Python 2.7 和 Python 3.7 中运行相同的代码,但是由于 Python 编译器的改进和不断发展,错误并不相同。


修复 Python 中 ValueError: invalid literal for float()

要修复值错误 invalid literal for float()could not convert string to float ,您需要提供一个有效的文字作为 float() 函数的参数,以便它可以正确解析它。

您可以为 float 函数提供有效的数字字符串(仅限数字)或整数值以完美运行。

代码:

h = input("Enter you height:")
print(type(h))

height = float(h)
print("\nYour height is:", height)
print(type(height))

输出:

Enter you height:5.4
<class 'str'>

Your height is: 5.4
<class 'float'>

height 的值始终是 float,但 input 语句将每个输入都作为字符串。 所以,在上面的例子中,用户输入了他们的身高“5.4”,其类是 str,但后来我们将其类型转换为“float”。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便