Serious Ruffy
Serious Ruffy

Reputation: 817

Python error: could not convert string to float - Only number from a string

I have some Python code that pulls strings out of the crwaling output. My code so far:

 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)

This gives an error:

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

Why can't '27,44\xa0€'be converted to a float? I guess because of the fact that I have

 \xa
  €

in my float which prevents parsing.

Can you guys help me out? Any feedback is appreciated

Upvotes: 1

Views: 4963

Answers (1)

m0dem
m0dem

Reputation: 1008

...
# 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

Upvotes: 4

Related Questions