Convert '165.0' to int

Frank Millman frank at chagford.com
Sun Jul 24 02:53:27 EDT 2011


On Jul 23, 5:12 pm, Billy Mays <no... at nohow.com> wrote:
> On 7/23/2011 3:42 AM, Chris Angelico wrote:
>
>
>
> > int(s.rstrip('0').rstrip('.'))
>
> Also, it will (in?)correct parse strings such as:
>
> '165............00000000000000'
>
> to 165.
>
> --
> Bill

True enough.

If I really wanted to be 100% safe, how about this -

    def get_int(s):
        if '.' in s:
            num, dec = s.split('.', 1)
            if dec != '':
                if int(dec) != 0:
                    raise ValueError('Invalid literal for int')
            return int(num)
        return int(s)

Frank



More information about the Python-list mailing list