ValueError:无法将字符串转换为float:' 1'

时间:2014-06-12 11:13:03

标签: python python-2.7 floating-point

我很困惑,因为我确认我尝试转换为float的变量确实是一个字符串(我将在此处显示我的日志):

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

我按如下方式计算:

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

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

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

似乎这应该是直截了当的。但我不明白为什么我会收到这个错误。有谁能发现问题?

谢谢!

1 个答案:

答案 0 :(得分:9)

您有一个嵌套字符串,即ratingX = "'1'"

values = ["('1', '1')", "('1', '1')"]

为起点

我建议先将其改为您想要的格式:

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)