Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python locale.setlocale() Function



The Python locale.setlocale() function is used to set the locale for the current program. The locale setting affects locale-aware functions such as formatting numbers, dates, and currency based on regional settings.

This function is particularly useful when dealing with internationalization, where different regions have distinct conventions for representing data.

Syntax

Following is the syntax of the Python locale.setlocale() function −

locale.setlocale(category, locale)

Parameters

This function accepts the following parameters −

  • category: Specifies the part of the locale to be set. Common categories include locale.LC_ALL (all locale settings), locale.LC_NUMERIC (numeric formatting), locale.LC_TIME (date/time formatting), and others.
  • locale: A string representing the locale to be set (e.g., "en_US.UTF-8" for US English). Passing an empty string "" uses the system’s default locale.

Return Value

This function returns the new locale setting as a string.

Example 1

Following is an example of the Python locale.setlocale() function. Here, we set the locale to US English −

import locale

locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
print(locale.getlocale())

Following is the output of the above code −

('en_US', 'UTF-8')

Example 2

Here, we change the locale to French and format a number using the locale settings −

import locale

locale.setlocale(locale.LC_ALL, "fr_FR.UTF-8")
number = 1234567.89
formatted_number = locale.format_string("%d", number, grouping=True)
print(formatted_number)

Output of the above code is as follows −

1 234 567

Example 3

Now, we use locale.setlocale() function to format currency based on a specified locale −

import locale

locale.setlocale(locale.LC_ALL, "de_DE.UTF-8")
currency = locale.currency(1234.56, grouping=True)
print(currency)

The result obtained is as shown below −

1.234,56 €

Example 4

We can retrieve the current locale setting without changing it using the locale.getlocale() function −

import locale

current_locale = locale.getlocale()
print("Current Locale:", current_locale)

The result produced is as follows −

Current Locale: ('C', 'UTF-8')
python_modules.htm
Advertisements