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

时间:2014-05-09 15:11:35

标签: python python-3.x

我收到此错误:

ValueError: could not convert string to float: '$39.99'

有人可以告诉我我的代码有什么问题吗?

import urllib.request

price = 99.99

while price > 4.74:

    page = urllib.request.urlopen("http://www.shoplavazza.com/products")
    text = page.read().decode("utf8")

    where = text.find('>$')

    start_of_price = where + 1

    end_of_price = start_of_price + 6

    price = float(text[start_of_price:end_of_price])

print("buy")

2 个答案:

答案 0 :(得分:3)

你必须这样做:

start_of_price = where + 2    #instead of 1

因此价格为39.99而不是$39.99无法投放为float)。

答案 1 :(得分:2)

where = text.find('>$') # returns the location of >, not the location of $
start_of_price = where + 1 # this is now 1 + the location above, in other words $
end_of_price = start_of_price + 6
text[start_of_price:end_of_price] # Go from $ to 6 characters later.

作为一个注释,你需要将6更改为5.毕竟

text = 'hello>$39.99'
where = text.find('>$') # 5
start_of_price = where + 2 #starting at character 7, the '3'
end_of_price = start_of_price + 6 # there are only 5 chars after the $
text[start_of_price:end_of_price] # !OH NOS!