How to convert a string "-2" into float in python?
>>> a=("-2","-2")
>>> float(a[0][0])开发者_开发问答
This gives me an error
ValueError: invalid literal for float(): -
So how do I convert it ?
Use a[0]
instead (a[0][0]
is the first character of the first element, not the first element).
Sorry, but your code has an error:
float(a[0])
will do. If you need 2.2 as result, then
x = 0.0; # python 2.x
for i in range(0, len(a)):
x += a[i] * 10**-i
It is one dimensional array, not multi dimensional array. So you have specify it as follows:
float(a[0])
float(a[1])
It can be specified that a[0] is the first place number '-2' and a[1] is the second place number '-2'. Try it.. I hope it should be helpful for you.
You're indexing incorrectly, if you want a tuple that contains floats for these two strings, then you have to do the following:
(float(a[0]), float(a[1]))
Note that the outer brackets are defining a new tuple.
精彩评论