Converting a string to the most probable type

hvendelbo.dev at googlemail.com hvendelbo.dev at googlemail.com
Fri Mar 7 09:53:36 EST 2008


On Mar 6, 9:17 pm, Luis M. González <luis... at gmail.com> wrote:
> On 6 mar, 11:27, Pierre Quentel <quentel.pie... at wanadoo.fr> wrote:
>
>
>
> > Hi,
>
> > I would like to know if there is a module that converts a string to a
> > value of the "most probable type" ; for instance :
> > - if the string is "abcd" the value is the same string "abcd"
> > - string "123" : value = the integer 123
> > - string "-1.23" (or "-1,23" if the locale for decimals is ,) : value
> > = the float -1.23
> > - string "2008/03/06" (the format is also locale-dependant) : value =
> > datetime.date(2008,03,06)
>
> > Like in spreadsheets, special prefixes could be used to force the
> > type : for instance '123 would be converted to the *string* "123"
> > instead of the *integer* 123
>
> > I could code it myself, but this wheel is probably already invented
>
> > Regards,
> > Pierre
> >>> 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')
>
> 'hello'

Neat solution. The real challenge though is whether to support
localised dates, these are all valid:
20/10/01
102001
20-10-2001
20011020



More information about the Python-list mailing list