Is there built-in way to check if string can be converted to float?

我的梦境 提交于 2021-01-29 07:26:13

问题


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?


回答1:


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 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

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




回答2:


I would suggest the ask for forgiveness not permission approach of using the try except clause:

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



回答3:


Easiest way would be to just try and turn it into a float.

try:
    float(str)
except ValueError:
    # not float
else:
    # is float


来源:https://stackoverflow.com/questions/64345057/is-there-built-in-way-to-check-if-string-can-be-converted-to-float

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!