ValueError: could not convert string to float: 

2019-08-10 11:05发布

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!

1条回答
聊天终结者
2楼-- · 2019-08-10 11:44

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)
查看更多
登录 后发表回答