Convert '165.0' to int
Frank Millman
frank at chagford.com
Sun Jul 24 03:58:39 EDT 2011
On Jul 24, 9:34 am, Steven D'Aprano <steve
+comp.lang.pyt... at pearwood.info> wrote:
> Frank Millman wrote:
> > 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)
>
> Consider what happens if you pass s = "42.-0".
>
Grrrr!
Ok, what if I change
if int(dec) != 0:
to
if [_ for _ in list(dec) if _ != '0']:
If I do this, I can get rid of the previous line -
if dec != ''
Am I getting closer?
Frank
More information about the Python-list
mailing list