isNumber? check

Skip Montanaro skip at
Mon Sep 29 23:05:40 CEST 2003

    >> if expr.strip("0123456789.e") == "": print "May be a number!"
    >> if expr.strip("0123456789") == "": print "Surely a number!"

    Rob> I don't like that solution for this particular project because, as
    Rob> you say yourself, if it says yes to the second question, it only
    Rob> *may* be a number.  I want to know for sure.

Expanding on my previous post, here are a couple *simple-minded* re's for
matching ints and floats (really, fixed-point numbers)

    >>> import re
    >>> ipat = re.compile("([0-9]+)$")
    >>> fpat = re.compile("([0-9]+\.[0-9]*$)")
    >>> token = "123"
    >>> fpat.match(token)
    >>> print fpat.match(token)
    >>> print ipat.match(token)
    <_sre.SRE_Match object at 0x40d6a0>
    >>> print ipat.match(token).group(1)
    >>> token = "123.456"
    >>> print ipat.match(token)
    >>> print fpat.match(token)
    <_sre.SRE_Match object at 0x487960>
    >>> print fpat.match(token).group(1)

Extension of this idea to useful definitions for your interpreter is left as
an exercise for the reader.


More information about the Python-list mailing list