Python atof with local input

社会主义新天地 提交于 2019-12-04 04:50:58

问题


Say, I have a (German) expression which reads 10.401,40 (in Mio EUR), I'd like to convert this to a real float (in this case around 10 billions) in Python.
This is what I have thus far:

import re, locale
from locale import *
locale.setlocale(locale.LC_ALL, 'de_DE') 

string = "10.401,40 (in Mio EUR)"
m = re.search(r'([\d.,]+)', string)
if m is not None:
    number = atof(m.group(1)) * 10**6

However, it raises a ValueError (ValueError: invalid literal for float(): 10.401.40).
Why? Isn't the .setlocale() directive supposed to be handling exactly this? Is there a pythonic way that I am (yet!) unaware of?


回答1:


I got the same ValueError. As this similar question explains, you need to have the German locale installed in your system. Following the above, I typed in sudo dpkg-reconfigure locales and selected de-DE.UTF-8. I had to modify the locale setting line to match with locale.setlocale(locale.LC_ALL, 'de_DE.utf8') and got your snippet to run. Good luck!



来源:https://stackoverflow.com/questions/35516947/python-atof-with-local-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!