Skip to content Skip to sidebar Skip to footer

Is There Built-in Way To Check If String Can Be Converted To Float?

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(

Solution 1:

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:
        returnfloat(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

Solution 2:

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 codepassexcept Exception as e: # which can be ValueError, or other's exceptions# deal with Exception, and it can be called using the variable eprint(f"Exception was {e}") # python >= 3.7passexcept Exception as e: # for dealing with other Exceptionpass# ... as many exceptions you would need to handlefinally:
    # do something after dealing with the Exceptionpass

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

Solution 3:

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

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

Post a Comment for "Is There Built-in Way To Check If String Can Be Converted To Float?"