Search code examples
pythonlocale

Fetching currency name for a provided Locale (Python)


I'm looking for a way to fetch a Currency name for a provided Locale. For example:

currency_name = get_currency_name(locale = "en_US")
print(currency_name) --> "US Dollar" 

Been scanning the Internet for the answer but can't find anything really helpful. This is as far as I've come:

import pycountry

country = pycountry.countries.get(name='Norway')
currency = pycountry.currencies.get(numeric=country.numeric)
currency_name = currency.name
print(currency_name) --> "Norwegian Krone"

Thanks!


Solution

  • import locale
    import babel
    from babel import numbers
    
    def get_currency_name(loc):
      l = locale.setlocale(locale.LC_ALL, '')
      locale.setlocale(locale.LC_ALL, loc)
      sym = locale.localeconv()['int_curr_symbol']
      print(babel.numbers.get_currency_name(sym, locale='en_US'))
      locale.setlocale(locale.LC_ALL, l)
    
    get_currency_name('en_US')
    get_currency_name('zh')
    get_currency_name('de')
    

    The output is

    US Dollar
    Chinese Yuan
    Euro