[Tutor] Doing the Right Thing when converting strings to numb ers

alan.gauld@bt.com alan.gauld@bt.com
Wed, 22 May 2002 15:27:00 +0100


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

The easy way would be to use eval()
All the usual caveats around using eval() 
(and exec()) apply of course....

def clever_coerce(mystr): return eval(mystr)

> 
> >>> 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 

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld