Reputation: 7921
I am parsing a bank's website to get the exchange rate.
However the format they return is "61,8000"
and it's a string.
I've tried float()
but it throws an error.
And the last thing I've tried is:
sell = "{:10.6f}".format( e.select_one('.prodazenVal').text.strip() )
buy = "{:10.6f}".format( e.select_one('.kupovenVal').text.strip() )
middle = "{:10.6f}".format( e.select_one('.sredenVal').text.strip() )
I get the following error:
Traceback (most recent call last):
File "jobs/fetchExchangeRate.py", line 28, in <module>
sell = "{:10.4f}".format( e.select_one('.prodazenVal').text.strip() )
ValueError: Unknown format code 'f' for object of type 'str'
I want to get: "61.8000"
Any suggestions?
Upvotes: 1
Views: 75
Reputation: 337
You can use Python to change to a locale that uses the comma as the decimal separator, such as Russian, like this:
import locale
locale_backup = locale.getlocale(locale.LC_NUMERIC)
locale.setlocale(locale.LC_NUMERIC, locale='ru_RU')
sell = "{:10.6f}".format(locale.atof(e.select_one('.prodazenVal').text.strip()))
buy = "{:10.6f}".format(locale.atof(e.select_one('.kupovenVal').text.strip()))
middle = "{:10.6f}".format(locale.atof(e.select_one('.sredenVal').text.strip()))
locale.setlocale(locale.LC_NUMERIC, locale_backup)
The locale.atof
method can be used to convert a localized numeric string to float.
Upvotes: 2
Reputation: 24107
This is kinda ugly, but will work:
def format_to_float(string):
return "{:10.6f}".format(float(string.strip().replace(",", ".")))
sell = format_to_float(e.select_one('.prodazenVal').text)
buy = format_to_float(e.select_one('.kupovenVal').text)
middle = format_to_float(e.select_one('.sredenVal').text)
We first strip()
all whitespace, then replace()
the comma with a dot to make "61,8000"
-> "61.8000"
, and then call float()
on it, before format()
ting it.
Upvotes: 0