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

您所在的位置:网站首页 python中+str()+ python string转float报ValueError: could not convert string to float

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

2023-03-23 10:55| 来源: 网络整理| 查看: 265

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 "", line 1, in 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"等等


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3