Convert '165.0' to int

Dan Stromberg drsalists at
Sun Jul 24 00:38:13 EDT 2011

On Sat, Jul 23, 2011 at 8:53 PM, Billy Mays <noway at> wrote:

> I'll probably get flak for this, but damn the torpedoes:
> def my_int(num):
>    import re
>    try:
>        m = re.match('^(-?[0-9]+)(.0)?$', num)
>        return int(
>    except AttributeError:
>        #raise your own error, or re raise
>        raise

I'd just been thinking, when I read your post, "It galls me a bit, but a
regex might be good for this".  I'd use a slightly different one though:

>>> import re
>>> m = re.match('^(-?\d+)(\.0*)?', '123')
>>> m.groups(1)
('123', 1)

This way the meaning of "a digit" is localized, and 0 or more trailing 0's
work.  BTW, Are there any cultures that don't use arabic numerals?  They
seem pretty ubiquitous.  I guess China uses arabic numerals most of the time
and their own traditional system sometimes, but I'm not sure that counts for
this issue.

Another decent way to go, would be to use:

>>> '123.00'.partition('.')
('123', '.', '00')
>>> '123'.partition('.')
('123', '', '')

...and then check that the 3rd element of the tuple is zero or more 0's,
perhaps using rstrip and comparing to a null string afterward.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list