Convert '165.0' to int

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Jul 24 03:34:17 EDT 2011


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".
-- 
Steven


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /