ActiveState Code

Recipe 225674: Verify if an argument is a valid number


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

Discussion

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.

Comments

  1. 1. At 3:26 p.m. on 30 sep 2003, Gregor Rayman said:

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

  2. 2. At 2:20 a.m. on 1 oct 2003, Rogier Steehouder said:

    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
    
  3. 3. At 7:56 p.m. on 23 mar 2005, Chris Hobbs said:

    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
    

Sign in to comment