ValueError:无法将字符串转换为浮点数:“1” [英] ValueError: could not convert string to float: '1'

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

问题描述



<$ p $

p> >>>打印评级xf
'1'
>>>打印类型(ratingXf)
< type'str'>
>>> ratingX = float(ratingXf)
ValueError:无法将字符串转换为float:'1'

我计算如下:

  rateX,rateY = v.split(',')
ratingXf = (rateX [1:])
ratingX = float(ratingXf)

当我尝试将字符串转换为整数,我得到以下错误:

  ValueError:无效的字面值为int()与基10: '1'

看起来这应该很简单。但我不明白为什么我得到这个错误。任何人都可以发现问题吗?



谢谢!

解决方案

嵌套字符串,即 ratingX =1
$ b

对于 values = [('1','1'),('1','1' )]



我建议把它变成你想要的格式:

 values_cleaned = map(clean_cell,values)

#然后迭代
在values_cleaned中进行评级:
if(len(rating)== 2):
ratingX,ratingY = rating [0],rating [1]#这一步可能不是必须的:P
deal_with_ratings(ratingX,ratingY)


I am throughly confused as I confirmed that the variable I am trying to convert to a float is indeed a string (I will show my log here):

>>> print ratingXf
'1'
>>> print type(ratingXf)
<type 'str'>
>>> ratingX = float(ratingXf)
ValueError: could not convert string to float: '1'

And I calculate it as follows:

rateX, rateY= v.split(',')
ratingXf = (rateX[1:])
ratingX = float(ratingXf)

And when I try to convert the string to an integer, I get the following error:

ValueError: invalid literal for int() with base 10: "'1'"

Seems this should be straightforward. But I do not understand why I am getting this error. Can anyone spot the problem?

Thanks!

解决方案

You have a nested string i.e. ratingX = "'1'".

For your starting point of values = ["('1', '1')", "('1', '1')"]

I suggest getting it into the format you want first:

clean_cell = lambda x: map(float, re.findall(r'\'([0-9]+)\'', x))
values_cleaned = map(clean_cell, values)

# Then iterate
for rating in values_cleaned:
    if (len(rating) == 2):
        ratingX, ratingY = rating[0], rating[1] # This step is probably not necessary :P
        deal_with_ratings(ratingX, ratingY)

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

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