[Tutor] Doing the Right Thing when converting strings to numbers
Michael Williams
michael.williams@st-annes.oxford.ac.uk
Mon, 20 May 2002 16:21:50 +0100
Hi,
I'd like to convert a string to either a float or an integer
``intelligently", i.e.:
>>> mystring = '5'
>>> mynumber = clever_coerce(mystring)
>>> print mynumber, type(mynumber)
5 <type 'int'>
>>> mystring = '4.9'
>>> mynumber = clever_coerce(mystring)
>>> print mynumber, type(mynumber)
4.9 <type 'float'>
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
or, if not, perhaps there should be. Could someone suggest how I might
go about writing one myself.
--
Michael