python string转float报ValueError: could not convert string to float

string转float的方法

python中,可以使用内置的float()函数将字符串string对象作为形参进行类型的转换,并以浮点数的类型值返回,并不修改原字符串string对象。语法如下:

float( strObj )

ValueError: could not convert string to float

使用float()函数来转换字符串为浮点数是,python抛出ValueError,并提示,could not convert string to float,意思是无法将参数指定的字符串转换为浮点数float类型的值,这是为什么呢?这是因为能够被float()函数转换的字符串需要满足数值型的字符串,比如“1.2”、“3”、“-1.01”等等。如下方的实例:

>>> float('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'a'

解决方法,及相关实例

可以通过try…except语句,来处理float()方法转换string过程中可能抛出的ValueError,让程序继续执行,如下代码:

#-*- coding:utf-8 -*-
def str2float(arg):
    try:
        a = float(arg)
        return a
    except ValueError as err:
        return '请输入数值型字符串,比如"1.2"、"2.5"、"-3"等等'

print(str2float("666"))
print(str2float("abc"))
#命令行输入运算python文件命令,比如:python3 test.py得到输出:
666.0
请输入数值型字符串,比如"1.2"、"2.5"、"-3"等等
python全栈: 笨鸟工具,python全栈
原文地址: python string转float报ValueError: could not convert string to float

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
心中带点小风骚的头像心中带点小风骚普通用户
上一篇 2023年9月15日
下一篇 2023年9月15日

相关推荐