[Tutor] Doing the Right Thing when converting strings to numbers

Alexandre Ratti alex@gabuzomeu.net
Mon, 20 May 2002 18:51:44 +0200


Hi Michael,


At 11:46 20/05/2002 -0400, you wrote:
>Date: Mon, 20 May 2002 16:21:50 +0100
>From: Michael Williams <michael.williams@st-annes.oxford.ac.uk>
>Subject: [Tutor] Doing the Right Thing when converting strings to numbers

>I'd like to convert a string to either a float or an integer
>``intelligently", i.e.:

>The string should ideally also be coerced into a float in the event of
>it being, e.g. '5.0'. Does such a function exist in the standard library

I'm not aware of such a function.

>Could someone suggest how I might  go about writing one myself.

Maybe you could test whether the initial string contain a decimal separator 
(a dot in your example).

 >>> def convert(value):
...     if "." in value:
...             return float(value)
...     else:
...             return int(value)

If your input strings are fairly standard (eg. they cannot contain 
sentences and you always use a dot as decimal separator), it should work.


Cheers.

Alexandre