isnumeric (mhlib.py)

Steve Holden sholden at holdenweb.com
Thu Jan 4 10:58:55 EST 2001


Richard van de Stadt <stadt at cs.utwente.nl> wrote in message
news:3A548B2A.B45DC580 at cs.utwente.nl...
> Hi,
>
> I needed a function to check if a string is a number.
> mhlib contains a function called isnumeric(), so I
> used that one. This is how it determines if a string
> is a number:
>
> numericprog = re.compile('^[1-9][0-9]*$')
> def isnumeric(str):
>     return numericprog.match(str) is not None
>
> However, this way, '0' is not regarded as a number.
> Is that what isnumeric is supposed to do?
>
Well, I suppose the obvious answer is that what you see is good enough for
mhlib's purposes, so at worst you might complain that the function isn't
very well named.  Of course the code doesn't document its purpose well, so
you fell in the hole.

> I don't know what the meaning of isnumeric for mh is,
> but why isn't numericprog simply like this:
>
> numericprog = re.compile('^[0-9]*$')
>
> Richard.
>
Again, if that will do for your purposes then go ahead and use it --
although I suspect you might not want the empty string to be considered a
number, in which case you might prefer the pattern to be

    '^[0-9]+$'

which will insist on seeing at least one digit.

I seem to remember there was a long discussion on validating numerics some
time ago on this list.  A lot depends on how rigorous you want to be,
whether you are interested in integers, long integers, reals or complexes,
etc.  If this is a test which is performed infrequently (such as, for
example, when analyzing lines of interactive input) probably the best
approach is to ask Python to convert using an explicit conversion function
such as int() or float(), trapping errors and handling them appropriately.

Apart form anything else, this allows you

a) to be sure the number is acceptable to Python in the appropriate context,
since value checking will also be performed, and

b) to avoid the import of a module you may not otherwise need.

regards
 Steve







More information about the Python-list mailing list