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

Michael Williams michael.williams@st-annes.oxford.ac.uk
Mon, 20 May 2002 17:39:10 +0100


On Mon, May 20, 2002 at 04:40:15PM +0100, ibraheem umaru-mohammed wrote:
> [Michael Williams wrote...]
> -| 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'>
>
> >>> s1='5'
> >>> n1=int(s1)
> >>> print n1,type(n1)
> >>> 5 <type 'int'>
> >>> s2='4.9'
> >>> n2=float(s2)
> >>> print n2,type(n2)
> >>> 4.9 <type 'float'>
> >>> 

I think you've misunderstood as I wasn't clear enough. I want to use the
*same* function to do the conversion to both float and int. I am writing
a program to read a series of numbers in from file. They are of unknown
type (i.e. whether they're float or int) so it would be simplest to
have/write a function that converted to float if the number ended
contained a period, or in if it did not. It is no trouble for me to
write such a function myself, but I was just asking whether it had
already been done.

-- 
Michael