Converting a string to the most probable type

castironpi at gmail.com castironpi at gmail.com
Sat Mar 8 20:33:51 CET 2008


On Mar 8, 12:05 pm, Pierre Quentel <quentel.pie... at wanadoo.fr> wrote:
> > >>> 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

In particular, you can retain access to the user/interface, and always
just query when probabilities aren't 100%.  In general, retain access
to a higher power, such as offering a hook ( def butdonotguess( raw,
guesses ):).  If you're making the decision, and a case-by-case is too
expensive, then you've made a policy, and someone gets shaft "'cause
policy".  You can throw an exception that's guaranteed to be handled
or exits.  '121212' isn't as bad as '121110'!  If you want to find out
who and when writes dates like that, apply to PR.  Obviously a person
knew at one point what the string was; how much is left?

P.S.  def welltheydidthatthistime( raw, guesses ):.



More information about the Python-list mailing list