【发布时间】:2013-10-29 13:29:53
【问题描述】:
当我在程序中使用float() 方法时,我收到一个错误。你能帮我解决这个问题吗?我正在使用 python 3.4.0a4。
这是程序:
import urllib.request
price = 99.99
while price > 4.74:
page = urllib.request.urlopen("http://www.beans-r-us.biz/prices.html")
text = page.read().decode("utf8")
where = text.find('>$')
start_of_price = where + 2
end_of_price = start_of_price + 4
price = float(text[start_of_price:end_of_price])
Print("Buy!")
这是我得到的错误:
Traceback (most recent call last):
File "F:/Python/python 8.py", line 11, in <module>
price = float(text[start_of_price:end_of_price])
ValueError: could not convert string to float: '!DOC'
【问题讨论】:
-
你找错了
>$。如果您正在解析 HTML,请考虑改用 HTML 解析器,例如 BeautifulSoup。 -
除非你预先定义了
Print,否则你会在最后一行得到一个NameError,因为它应该是print。记住 Python 区分大小写。 -
您的切片字符串,
text[start_of_price:end_of_price]不是数字。 -
另外一个问题,用浮点数的钱进行计算是不明智的,它们不能全部被计算完全准确地存储,因此可能会出现舍入错误。相反,您应该使用整数或 Decimal 模块来保存便士的数量。
标签: python runtime-error traceback