[Tutor] string to int or float

Jimmy verma jim_938 at hotmail.com
Mon Nov 3 08:26:39 EST 2003


Yes that worked for me. Thanks a lot for your suggestions.

Really this list is of great help as it is having helpful persons around.

Thanks again to everyone for their suggestions.



>From: Gonçalo Rodrigues <op73418 at mail.telepac.pt>
>To: tutor at python.org
>Subject: Re: [Tutor] string to int or float
>Date: Mon, 03 Nov 2003 12:43:55 +0000
>
>On Mon, 03 Nov 2003 17:45:58 +0530, you wrote:
>
> >Hello,
> >
> >I want to convert a list of strings to list of integers:
> >
> >e.g.
> >
> >List = ['207','-308','-8.0','6']
> >
> >and i want it like this
> >
> >list = [207, -308, -8.0, 6]
> >
> >i am trying to do it with int and float functions
> >But i dont know how i can check whether the string will be for float
> >function or int function.
> >
> >for i in range(len(list)):
> >      t = int(list[i])
> >
> >But this will give error when it will encounter '-8.0' as it should be
> >submitted to float()
> >
> >
> >Is there any pythonic way to check whether i should use int or float.
> >
>
>The key is the Python interpreter:
>
> >>> int("-0.1")
>Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
>ValueError: invalid literal for int(): -0.1
>
>OK, int raises ValueError on an invalid string. Then we can use the
>try, except block to catch the exception and try float. Something
>like:
>
> >>> def convertStr(s):
>... 	"""Convert string to either int or float."""
>... 	try:
>... 		ret = int(s)
>... 	except ValueError:
>... 		#Try float.
>... 		ret = float(s)
>... 	return ret
>...
>
>Now let us test it
>
> >>> convertStr("1")
>1
> >>> convertStr("0.1")
>0.10000000000000001
> >>> convertStr("")
>Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
>   File "<interactive input>", line 7, in convertStr
>ValueError: empty string for float()
> >>>
>
>OK, it's working as we want it.
>
>Now, the rest is up to you :-)
>
>With my best regards,
>G. Rodrigues
>
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor

_________________________________________________________________
Discover digital jadoo! Enter this contest. 
http://server1.msn.co.in/sp03/mediacenter/index.asp Win cool prizes!




More information about the Tutor mailing list