为了账号安全,请及时绑定邮箱和手机立即绑定

是否有内置方法来检查字符串是否可以转换为浮点数?

是否有内置方法来检查字符串是否可以转换为浮点数?

PHP
GCT1015 2023-11-09 16:47:30
我知道有一些方法可以检查 str 是否可以使用 try- except 或正则表达式进行转换,但我一直在寻找(例如) str 方法,例如str.isnumeric()str.isdigit()str.isdecimal() # also doesn't work for floats但找不到任何。还有我还没找到的吗?
查看完整描述

3 回答

?
慕标琳琳

TA贡献1830条经验 获得超9个赞

我建议使用 try except 子句请求宽恕而不是许可方法:


str_a = 'foo'

str_b = '1.2'


def make_float(s):

    try:

        return float(s)

    except ValueError:

        return f'Can't make float of "{s}"'

>>> make_float(str_a)

Can't make float of "foo"

>>> make_float(str_b)

1.2


查看完整回答
反对 回复 2023-11-09
?
www说

TA贡献1775条经验 获得超8个赞

Try except 子句的形式如下:


try:

    # write your code

    pass

except Exception as e: # which can be ValueError, or other's exceptions

    # deal with Exception, and it can be called using the variable e

    print(f"Exception was {e}") # python >= 3.7

    pass

except Exception as e: # for dealing with other Exception

    pass

# ... as many exceptions you would need to handle

finally:

    # do something after dealing with the Exception

    pass



查看完整回答
反对 回复 2023-11-09
?
萧十郎

TA贡献1815条经验 获得超12个赞

最简单的方法就是尝试将其变成浮动。


try:

    float(str)

except ValueError:

    # not float

else:

    # is float


查看完整回答
反对 回复 2023-11-09
  • 3 回答
  • 0 关注
  • 66 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信