[Tutor] string to int or float

Gonçalo Rodrigues op73418 at mail.telepac.pt
Mon Nov 3 07:43:55 EST 2003

On Mon, 03 Nov 2003 17:45:58 +0530, you wrote:

>I want to convert a list of strings to list of integers:
>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

>>> 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")
>>> convertStr("0.1")
>>> 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

More information about the Tutor mailing list