[Tutor] PyCountry currency formatting woes
Peter Otten
__peter__ at web.de
Mon May 5 10:10:28 CEST 2014
Sithembewena Lloyd Dube wrote:
> Thanks, i was actually getting the error information to update the post.
> Apoligies to waste your time posting here - I could not find an
> appropriate PyCountry discussion list and my next best bet seemed to be a
> Python users' list.
>
> For those who care to look, the error is as follows (a concise example
> from an interactive shell:
>
> import pycountry
> country = pycountry.countries.get(alpha2='DE')
> currency = pycountry.currencies.get(numeric=country.numeric)
> Traceback (most recent call last):
> File "", line 1, in
> File "/usr/lib/pymodules/python2.6/pycountry/db.py", line 83, in get
> return self.indices[field][value]
> KeyError: '276'
>
> The obvious issue here is that the pycountry.countries collection does not
> contain a currency with a numeric of 276 (Germany's numeric) - yet it does
> contain the Euro. Any ideas as to what the way around this may be?
It looks like the development version of babel
http://babel.pocoo.org/docs/api/numbers/#babel.numbers.get_territory_currencies
can do what you want:
$ LANG=en_US.UTF-8 python
Python 2.7.5+ (default, Feb 27 2014, 19:37:08)
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import babel.numbers as bn
>>> bn.get_territory_currencies("DE")
['EUR']
>>> print bn.format_currency(1.234, "EUR")
€1.23
>>> print bn.format_currency(1.234, "EUR", locale="DE")
1,23 €
>>> import babel
>>> babel.__version__
'2.0-dev'
More information about the Tutor
mailing list