Welcome, guest | Sign In | My Account | Store | Cart

This recipe uses a regular expression to determine whether or not the argument to the function is in a numeric format (integer, floating point, scientific, or engineering).

Python, 13 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def is_a_number(x):
    """This function determines if its argument, x, is in the
    format of a number. It can be number can be in integer, floating
    point, scientific, or engineering format. The function returns True if the
    argument is formattted like a number, and False otherwise."""
    
    import re
    num_re = re.compile(r'^[-+]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][-+]?[0-9]+)?$')
    mo = num_re.match(str(x))
    if mo:
        return True
    else:
        return False

When carrying out computations based on user-supplied arguments, it is somethimes useful to confirm that these arguments are in an acceptable numeric format before performing the calculations.

The regular expression used in this recipe might have to be changed depending on the locale.

3 comments

Gregor Rayman 20 years, 7 months ago  # | flag

unicode. str(x) can fail and throw an exception, if x is unicode

Rogier Steehouder 20 years, 7 months ago  # | flag

Different approach. I suggest the following (works for 2.3, don't know about earlier versions):

def is_a_number(x):
    try:
        float(x)
        return True
    except ValueError:
        return False
Chris Hobbs 19 years, 1 month ago  # | flag

Need to check for lists. This method works nicely to detect strings, etc being passed as parameters into a function when only numeric values are allowed. It fails, however, if the parameter passed in is a list. To avoid problems there, augment the method a trifle:

def is_a_number(x):
    try:
        float(x)
        return True
    except ValueError:
        return False
    except TypeError:
        return False