Search code examples
pythonwindowspython-2.7localesetlocale

How to change locale in python in windows?


I want to format price in integer to properly formatted currency. Example 10000 to or ₹10,000

So, I am using the following commands in python

import locale
locale.setlocale(locale.LC_MONETARY, 'en_US')
or
locale.setlocale(locale.LC_MONETARY, 'en_IN')
print str(locale.currency(10000, grouping=True))

When I use the above commands in python in ubuntu in different laptop, they are working perfectly fine. But, on windows they are not working.

Its giving me error as follows

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\locale.py", line 581, in setlocale
    return _setlocale(category, locale)
locale.Error: unsupported locale setting

How to solve this error ?

I am using Windows 10. I open cmd and type "python" enter. The python shell is presented with following version. There I type the above commands.

Python 2.7 (r27:82525, Jul  4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32

Note :- I tried copying the locale.py file from python directory in ubuntu system to Windows directory i.e., "C:\Python27\Lib" but its still not working.


Solution

  • You can take a look at the pycountry library to have a mapping between Windows and Linux language codes:

    >>> pycountry.languages.lookup('fr')
    Language(alpha_2=u'fr', alpha_3=u'fra', bibliographic=u'fre', name=u'French', scope=u'I', type=u'L')
    >>> pycountry.languages.lookup('french')
    Language(alpha_2=u'fr', alpha_3=u'fra', bibliographic=u'fre', name=u'French', scope=u'I', type=u'L')
    >>> pycountry.languages.lookup('chinese')
    Language(alpha_2=u'zh', alpha_3=u'zho', bibliographic=u'chi', name=u'Chinese', scope=u'M', type=u'L')
    >>> pycountry.languages.lookup('chinese-traditional')
    Traceback (most recent call last):
      ...
    LookupError: Could not find a record for 'chinese-traditional'
    

    Then you can do:

    import os
    import locale
    import pycountry
    
    lang = "en_IN"  # your code
    language = pycountry.languages.lookup(lang)
    if os.name == "posix":
        locale.setlocale(locale.LC_MONETARY, language.alpha_2)
    else:
        locale.setlocale(locale.LC_MONETARY, language.name)
    

    EDIT

    To format currency values, you may consider using Babel, for instance:

    >>> babel.numbers.format_currency(10000, 'INR', locale='en_IN')
    u'\u20b9\xa010,000.00'
    
    >>> print(babel.numbers.format_currency(10000, 'INR', locale='en_IN'))
    ₹ 10,000.00