[Tutor] Re: Question on Regular Expression Help

Jeff Shannon jeff@ccvcorp.com
Mon Feb 10 15:01:18 2003


Magnus Lycka wrote:

>
> I think the code below works, but I don't really like it... I'm a bit
> allergic to comparing floats for equality, even though I think it
> should work in this particular case. [...]
>
> >>> def isInt(s):
> ...     try:
> ...             return int(s) == float(s)
> ...     except:
> ...             return False 


As long as an integer is always exactly representable as a float (that 
is, a number 2343265.00 can be exactly represented in float format), 
which I believe to be the case, then this will work.

However, the O.P.'s problem didn't specify that it was necessary to find 
integers, just that it was necessary to find "numbers".  In this case, 
the format of the input file would be the key -- if the numbers there 
are always given as integer values, then testing whether int(value) 
throws an exception is enough.  If the numbers sometimes have decimal 
places (or, indeed, even if they are always integers) then testing 
whether float(value) throws an exception will work.  Since the 
integer-ness (integrity?) of the number is irrelevant, it's not 
necessary to do both and compare the result.  So, my suggestion to the 
O.P. would be this little snippet:

def IsNumber(val):
    try:
        float(val)
        return True
    except:
        return False

temps = [x for x in inputstring.split() if IsNumber(x)]

Now 'temps' is a list of strings which contain only numeric values. 
 Note that we're not saving the numeric value, we're only noting that 
these strings *can* be converted to numbers -- this will be important 
later on when actually using the number in question.  If we will need 
them as numbers later, the following code might be more effective:

temps = []
for item in inputstring.split():
    try:
        x = float(item)
        temps.append(x)
    except:
        pass

Now we have a list of floats.  Of course, if we really want integers 
then int(item) will work just as well as float(item) -- or even 
int(float(item)), if we want to accept numbers with decimal values but 
truncate them to integers.

Jeff Shannon
Technician/Programmer
Credit International