Python 将解析后的数字格式化为浮点()
我正在分析一家银行的网站以获取汇率 但是,它们返回的格式是Python 将解析后的数字格式化为浮点(),python,python-3.x,Python,Python 3.x,我正在分析一家银行的网站以获取汇率 但是,它们返回的格式是“618000”,它是一个字符串 我尝试了float(),但它抛出了一个错误 我最后试过的是: 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.selec
“618000”
,它是一个字符串
我尝试了float()
,但它抛出了一个错误
我最后试过的是:
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() )
我得到以下错误:
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'
回溯(最近一次呼叫最后一次):
文件“jobs/fetchExchangeRate.py”,第28行,在
sell=“{:10.4f}”.format(例如,select_one('.prodazenVal').text.strip())
ValueError:类型为“str”的对象的格式代码“f”未知
我想得到:
“61.8000”
有什么建议吗?这有点难看,但可以:
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)
我们首先
strip()
所有空格,然后replace()
逗号加一个点,使“618000”
->“61.8000”
,然后调用float()
,然后format()
对其进行排序。您可以使用Python将逗号更改为十进制分隔符,例如俄语,像这样:
导入区域设置
locale\u backup=locale.getlocale(locale.LC\u NUMERIC)
setlocale(locale.LC\u NUMERIC,locale='ru\u ru')
sell=“{:10.6f}”。格式(locale.atof(e.select_one('.prodazenVal').text.strip())
buy=“{:10.6f}”。格式(locale.atof(e.select_one('.kupovenVal').text.strip())
middle=“{:10.6f}”。格式(locale.atof(e.select_one('.sredenVal').text.strip())
locale.setlocale(locale.LC\u数值,locale\u备份)
locale.atof
方法可用于将本地化数字字符串转换为浮点。我们不知道e.select_one('.prodazenVal').text.strip()是什么。你能插入实际的字符串吗?@peer它是618000
,如果你想在其他地方使用实际的语言环境,你必须始终记住在你使用它的任何地方更改语言环境。这是一个非常混乱的解决方案。@ruohola。我认为这比你的解决方案要随意得多,但是清理确实是不可取的。供参考: