ValueError:无法将字符串转换为浮点数:“1” [英] ValueError: could not convert string to float: '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中进行评级:
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屋!