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

The present recipe shows a function to check whether or not its argument is consistent with standard numerical formats: integer, floating point, scientific, or engineering.

Python, 8 lines
1
2
3
4
5
6
7
8
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 '1' if the argument is formattted
    like a number, and '0' otherwise."""
    import re 
    num_re = re.compile(r'^[-+]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][-+]?[0-9]+)?$')
    return str(re.match(num_re, x))) != 'None'

Often it is necessary to validate an entry as being a number before passing into another program or script. At the heart of the function is a regular expression consistent with numbers in integer, floating point, scientific, or engineering format.

2 comments

Matthew Wood 22 years, 8 months ago  # | flag

Efficiency... Would this not be more efficient if it were implemented as a callable class?

That way, you wouldn't have to re-build the re.compile() object each time you call the function.

Matthew Wood 22 years, 8 months ago  # | flag

Here is the sample code... I don't know why the code won't print out here. --------

!/usr/bin/env python

import re

class Is_A_Number :

    """This function/object determines if its argument, accused, is in the






    format of a number. It can be number can be in integer, floating point,






    scientific, or engineering format. The function returns '1' if the argument






    is formattted like a number, and '0' otherwise."""














    num_re = re.compile(r'^[-+]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][-+]?[0-9]+)?$')













    def __call__ (self, accused) :






            return str(re.match(self.num_re, accused))) != 'None'

End of the class

is_a_number = Is_A_Number()

Created by gyro funch on Wed, 22 Aug 2001 (PSF)
Python recipes (4591)
gyro funch's recipes (6)

Required Modules

  • (none specified)

Other Information and Tasks