Ask Your Question
1

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

asked 4 years ago

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)):
     A[i]=float(A[i])

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

Do I do something forbiden ?

Preview: (hide)

Comments

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 ( 4 years ago )

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

Cyrille gravatar imageCyrille ( 4 years ago )
2

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

John Palmieri gravatar imageJohn Palmieri ( 4 years ago )
1

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 ( 4 years ago )

1 Answer

Sort by » oldest newest most voted
0

answered 4 years ago

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]
Preview: (hide)
link

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

Stats

Asked: 4 years ago

Seen: 559 times

Last updated: Jul 07 '20