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教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.