Converting a string to the most probable type

Pierre Quentel quentel.pierre at wanadoo.fr
Sat Mar 8 13:05:55 EST 2008


> >>> def convert(x):
>
>         if '.' in x:
>                 try: return float(x)
>                 except ValueError: return x
>         else:
>                 try: return int(x)
>                 except: return x
>
> >>> convert('123')
> 123
> >>> convert('123.99')
> 123.98999999999999
> >>> convert('hello')
>
Hi,

That's fine for people who write floats with a "." ; but others learn
to enter them with ","

For the same float, the French write the literal 123.456.789,99 when
others write 123,456,789.99 ; for us, today is 8/3/2008 (or
08/03/2008) where for others it's 3/8/2008 or perhaps 2008/3/8

Popular spreadsheets know how to "guess" literals ; if the guess is
not correct users can usually specify the pattern to use. My question
was just to know if something similar had already been developed in
Python ; I understand that the answer is no

Thanks,
Pierre



More information about the Python-list mailing list