1

I have a list of strings (CD_cent) like this:

2.374 2.559 1.204

and I want to multiply these numbers with a float number. For this I try to convert the list of strings to a list of floats for example with:

CD_cent2=[float(x) for x in CD_cent]

But I always get the error: ValueError: could not convert string to float: '.'. I guess this means, that it can't convert the dot to a float (?!) But how could I fix this? Why doesn't it recognize the dot?

3
  • 1
    Is CD_cent == "2.374 2.559 1.204"? If so, for x in CD_cent will iterate over characters, ie, x = 2, x = '.', x = 3, etc. That's why it's complaining, because '.' can't be converted to float. Commented Jul 12, 2017 at 0:09
  • yes the command print(CD_cent) gives me '2.374 2.559 1.204' Commented Jul 12, 2017 at 0:12
  • oh ok... so do you have an idea how i could fix this? Commented Jul 12, 2017 at 0:13

2 Answers 2

12

You need to split each string as the string has multiple values:

your_str = "2.374 2.559 1.204"

floats = [float(x) for x in your_str.split(' ')]

Having a list you can do something like this:

li = [...]
floats = []

for s in li:
    floats.extend([float(x) for x in s.split(' ')])

In your exact situation you have a single string CD_cent = 2.374 2.559 1.204, so you can just:

floats = [float(x) for x in CD_cent.split(' ')]
Sign up to request clarification or add additional context in comments.

6 Comments

This is the right way to do it. But I would explicitly add str.split(" ") to make it clear how the string should be split.
@darksky, yes, sure, forgot to add ' '. Updated the answer. Thanks
Or even just split() without any arguments, so that this works with any kind of whitespace delimiter
Thanks guys! That was what i needed :)
Bleh, don't name strings str. str is the string class/constructor, and now you shadowed it.
|
0

When I ran your line with the provided data everything worked fine and all the strings converted to floats without error. The error indicates that somewhere in your CD_cent there is a single DOT . that really can't be converted to float.

To try to solve this do:

CD_cent2=[float(x) for x in CD_cent if x != '.']

And if that doesn't work because of other strings you will have to try...except like this:

CD_cent2 = []
for x in CD_cent:
    try:
        CD_cent2.append(float(x))
    except ValueError:
        pass

All of that is because I assume CD_cent is not just a long string like '2.374 2.559 1.204' but it is a list like [2.374,2.559,1.204]. If that is not the case than you should split the line like this

CD_cent2=[float(x) for x in CD_cent.split()]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.