简体   繁体   中英

How to get currency symbol from ISO country code in Django application?

I just want to get the Currency symbol for different countries in my Python Django application from the country code I have. For example I have a country code 'US', the output I need is '$' or 'US$'.

Now I achieve this with the help of two libraries, namely pycountry and forex-python. Can I achieve this in a more simple way?

import pycountry
from forex_python.converter import CurrencyCodes
code = "US"
country = pycountry.countries.get(alpha_2=code)
currency = pycountry.currencies.get(numeric=country.numeric)
country_codes = CurrencyCodes()
country_codes.get_symbol(currency.alpha_3)

Output:

You can do this using babel :

from babel.numbers import get_currency_symbol, get_territory_currencies

def currency_symbol(country_code):
    try:
        currency_code = get_territory_currencies(country_code)[0]
        symbol = get_currency_symbol(currency_code, locale='en_US')
    except IndexError:
        symbol = ''
    return symbol
    

Now print to get the output you need:

>>> print(currency_symbol('US'))
$

Notes:

  1. The function will return an empty string when it cannot find the country code you entered.
  2. The function will return the ISO code for the currency when the symbol does not exist for the given locale .

Modify the function according to your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM