I'm Sure There's A Better Way

Alex new_name at mit.edu
Fri Jul 6 22:29:13 EDT 2001


I may still be missing some cases, I did this a bit carelessly, but I
hope you get the idea.

import re

def isNum(s):

    try: float(s)
    except ValueError:

        # Python couldn't convert  it to a number, so  it's not in the
        # requested format.
        return None

    # Check that the precision is correct
    if '.' in s:
        l = list(s)
        assert l.count('.') == 1, \
               "Can't have more than one '.' in a number"

        if l.index('.') != len(s) - 3:

            # Wrong precision
            return None

    # Check that it begins with a number or '-' (it could start with a
    # '.')
    if not re.match('[-0-9]', s): return None
    
    return 1

if __name__ == '__main__':

    for s in ['9', '-1', '2.30', '-2.39',]: assert isNum(s)    

    for s in ['.01', '1.234', 'bub', '1.', '--1']: assert not isNum(s)

HTH.
Alex.



More information about the Python-list mailing list