我需要将欧洲大陆格式的字符串货币字符串转换为 float :
输入:
'6.150.593,22 €'
意识到小数点是逗号,千位分隔符是句点。
输出:
6150593.22
我读过这些问题,但它们只适用于美元货币和语言环境:
- How do I convert a currency string to a floating point number in Python?
- python: how to convert currency to decimal?
currency_euros='6.150.593,22 €'
float(currency_euros[:-2])
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
float(currency_euros[:-2])
ValueError: could not convert string to float: '6.150.593,22'
更新:按照@IrmendeJong 的回答:
>>> import locale
>>> locale.setlocale(locale.LC_NUMERIC, "es")
'es'
>>> print(locale.currency(6150593.22))
6150593,22 €
>>> money = '6.150.593,22 €'
>>> locale.atof(money)
Traceback (most recent call last):
File "<pyshell#68>", line 1, in <module>
locale.atof(money)
File "C:\Python35\lib\locale.py", line 318, in atof
return func(delocalize(string))
ValueError: could not convert string to float: '6150593.22 €'
>>>
我很惊讶 locale.currency() 可以正常工作,但它的倒数方法 locale.atof() 不起作用。
请您参考如下方法:
使用locale.atof https://docs.python.org/3/library/locale.html#locale.atof
>>> import locale
>>> locale.setlocale(locale.LC_NUMERIC,"nl")
'nl'
>>> locale.atof("6.150.593,22")
6150593.22
