有内置的方法来检查字符串是否可以转换为浮点数吗? [英] Is there built-in way to check if string can be converted to float?

查看:70
本文介绍了有内置的方法来检查字符串是否可以转换为浮点数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有多种方法可以检查是否可以使用try-except或正则表达式转换str,但是我一直在寻找(例如)str方法,例如

I know there are ways to check if str can be converted using try-except or regular expressions, but I was looking for (for example) str methods such as

str.isnumeric()
str.isdigit()
str.isdecimal() # also doesn't work for floats

但是找不到任何东西.我还没有找到吗?

but could't find any. Are there any I haven't found yet?

推荐答案

Macattack Jab ,您可以使用 try ,您可以在 w3school的教程.

As stated by and Macattack and Jab, you could use try except, which you can read about in python's docs or w3school's tutorial.

Try Except子句的格式为:

Try Except clauses have the form:

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

有关内置异常的列表,请参见 python的文档.

For a list of built-in Exceptions, see python's docs.

这篇关于有内置的方法来检查字符串是否可以转换为浮点数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆