[Tutor] Re: Question on Regular Expression Help
alan.gauld@bt.com
alan.gauld@bt.com
Mon Feb 10 12:10:04 2003
> But +42 is not an integer, right? This can be fixed of course.
>>> def isnumber(str):
... if str[0] in '+-':
... start = 1
... else:
... start = 0
Or replace the if/else with:
def isnumber(strng)
start = strng[0] in '+-'
... for c in strng[start:]:
... if c not in '0123456789':
... return False
... return True
But I prefer:
> Don Arnold wrote:
> >>> def isInt(aString):
> try:
> int(aString)
> return True
> except:
> return False
>
>But note that int(3.14) => 3 ! Is that what you want? Is 3.14 an integer?
Doesn't matter since we only return a boolean, if the number can
be converted to an int it is a number, thats all I care about here...
> import re
> def isInteger(s):
> return re.match(r'[+-]?\d+$', s)
I note we've changed the test now to isInteger from isNumber...
> From a performance point of view, the try/except version is
> the faster when the number is really and integer,
It's faster regardless, it just doesn't guarantee the number
is an integer.
> regular expression version is the slowest, but I think
> regular expression might win big if applied to a bigger problem,
Yes I agree, that's why I suggested it it to an earliuer poster
as the best flexible solution for dealing with strange unformatted
input.
> re.findall(r'\s([+-]?\d+)\s', s)
Just so.
Alan G.