ValueError:无法将字符串转换为float:“." [英] ValueError: could not convert string to float: '.'

查看:77
本文介绍了ValueError:无法将字符串转换为float:“."的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的字符串(CD_cent)列表:

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]

但是我总是收到错误: ValueError:无法将字符串转换为float:'.'.我想这意味着它无法将点转换为浮点(?!),但是我该如何解决呢?为什么它不识别点?

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?

推荐答案

由于字符串具有多个值,您需要分割每个字符串:

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(' ')])

在您的实际情况下,您只有一个字符串 CD_cent = 2.374 2.559 1.204 ,因此您可以:

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(' ')]

这篇关于ValueError:无法将字符串转换为float:“."的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆