pythoncastingfloating-pointtype-conversioninteger

How do I check if a string represents a number (float or int)?


How do I check if a string represents a numeric value in Python?

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

The above works, but it seems clunky.


Editor's note: If what you are testing comes from user input, it is still a string even if it represents an int or a float. For converting the input, see How can I read inputs as numbers? For ensuring that the input represents an int or float (or other requirements) before proceeding, see Asking the user for input until they give a valid response


Solution

  • Which, not only is ugly and slow

    I'd dispute both.

    A regex or other string parsing method would be uglier and slower.

    I'm not sure that anything much could be faster than the above. It calls the function and returns. Try/except doesn't introduce much overhead because the most common exception is caught without an extensive search of stack frames.

    The issue across programming languages is that any numeric conversion function has two kinds of results:

    C (as an example) hacks around this a number of ways. Python lays it out clearly and explicitly.

    I think your code for doing this is just fine. The only thing that could be cleaner is moving the return True into an else block, to be clear that it's not part of the code under test – not that there's much ambiguity.

    def is_number(s):
        try:
            float(s)
        except ValueError:  # Failed
            return False
        else:  # Succeeded
            return True