Python错误:无法将字符串转换为float - 仅限字符串中的数字

时间:2017-04-22 19:14:39

标签: python string floating-point numbers

我有一些Python代码可以将字符串从crwaling输出中拉出来。 到目前为止我的代码:

 import requests, json, bs4, csv, re
 import urllib

 response = urllib.request.urlopen('https://currency-api.appspot.com/api/USD/EUR.json')
 jsondata = json.loads(response.read().decode("utf-8"))
 Wechselkurs = (jsondata['rate'])


 jsonUrl = "https://www.jsox.de/s/results.json?&q=London& customerSearch=1&page=0
 response = session.get(jsonUrl, headers=headers)
 js_dict = (json.loads(response.content.decode('utf-8')))

 for item in js_dict:
 prices = js_dict['searchResults']["tours"]

     for price in zip(prices):
         price_final = price.get("price")["original"]
         if price_final:
            price_end = int(float(price_final)*100*Wechselkurs)
            print(price_end)

这会出错:

price_end = int(float(price_final)*100*Wechselkurs)
ValueError: could not convert string to float: '27,44\xa0€'

为什么不能将' 27,44 \ xa0&#39转换为浮点数?我猜是因为我有

 \xa
  €

在我的浮动中阻止解析。

你能帮助我吗?任何反馈都表示赞赏

1 个答案:

答案 0 :(得分:2)

...
# thanks for the suggestion @RobertSeaman
price_final = price_final[::-1].replace('.', ',').replace(',', '.', 1)[::-1].translate(None, "\xa0€,")
price_end = int(float(price_final) * 100 * Wechselkurs)
...

https://docs.python.org/2/library/string.html#string.translate