Ask Your Question

convert a string in float but not a list of string in list of float

asked 2020-07-07 04:00:26 -0500

Cyrille gravatar image

This is a very weird behaviour.

Suppose I have a list such

A=['1.2', '2.565', '3.45']

If I I create the command A[1]=float(A[1]) the result is

A=[1.2, '2.565', '3.45']

Now if I ask

for i in range(len(A)):

the result is ValueError: could not convert string to float:

Do I do something forbiden ?

edit retag flag offensive close merge delete


Please write the complete error message. What comes next is quite crucial. Probably your actual A contains strings with quotes or other extra characters (unlike the A you wrote here, which is fine and does not cause any error). Or if that is really the complete error message, then your A contains the empty string or a string consisting only of whitespace.

rburing gravatar imagerburing ( 2020-07-07 04:19:16 -0500 )edit

rburing ok I have verified there are null string on my data base. Do you know how eliminate them ?

Cyrille gravatar imageCyrille ( 2020-07-07 10:36:15 -0500 )edit

What does this question have to do with Sage? Isn't is just a plain Python question?

John Palmieri gravatar imageJohn Palmieri ( 2020-07-07 11:25:02 -0500 )edit

Perhaps you are true, but it happens in a Sage session. From the user point of view it is often difficult to know if it is a Sage problem or a Python one. I am an economist not a computer scientist. And, more than that, rburing was true, it was not a code problem but a data problem. I want use data but I also want that the link between data and theory be the most explicit. It's the reason why I have chosen Sage.

Cyrille gravatar imageCyrille ( 2020-07-07 23:42:07 -0500 )edit

1 answer

Sort by » oldest newest most voted

answered 2020-07-07 07:31:25 -0500

Sébastien gravatar image

This works:

sage: A = ['1.2', '2.565', '3.45']
sage: A = [float(a) for a in A]
sage: A
[1.2, 2.565, 3.45]
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2020-07-07 04:00:26 -0500

Seen: 108 times

Last updated: Jul 07