[Tutor] Re: Question on Regular Expression Help

Magnus Lycka magnus@thinkware.se
Sat Feb 8 13:00:02 2003


At 11:05 2003-02-08 -0600, Don Arnold wrote:
> > But note that int(3.14) => 3 ! Is that what you want? Is 3.14 an integer?
> >
>
>Nope: int(3.14) => 3, but int('3.14') raises an exception as intended.

True, but while the loop and re functions will throw a TypeError
for a float as input, your version will silently give the wrong
answer. With "return int(s) == float(s)" I *think* it will always
give the right result. (If we assume that a long is no int.)

As a user of a function I certainly prefer an exception to an
incorrect response if I use it differently than intended. (This
is regardless of whether I wrote it myself or not. ;)

In a way it might seem a bit strange that 3.14 is ok as an
argument, but "3.14" is not. With a float as an argument, int()
takes the role of truncator as well as type converter. With a
string input, it will refuse to truncate. But it's not so strange.
Floats are basically always approximations, while strings describe
exactly what they describe...

But I suppose the big issue is that the try: int() version will
check for complience with the memory bound Python int type, while
the re and loop version will check whether a string is mathematically
an integer, i.e. an int or a long.

Often, we want to use such values, and in such cases, we will want to
convert them to numeric types anyway. In that case it's obviously most
conveient to try: int().

Note that python automatically creates longs when you perform operations
where ints won't fit in recent versions of Python. So sys.maxint + 1 will
no longer raise an OverflowError, but will instead return a long. But
int(sys.maxint + 1) will still raise an OverfloError. Ints are faster
than longs though, so it might be good to do something like

try:
     x = int(s)
except OverflowError:
     x = long(s)
except:
     # Error handling...


-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se