locale
The Python locale
module provides tools to handle the localization of programs, such as formatting numbers, dates, and currencies according to the conventions of different locales. It allows you to access and modify the locale settings of your system.
Here’s an example:
>>> import locale
>>> # Set to a full-featured locale that supports currency
>>> locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
'en_US.UTF-8'
>>> locale.currency(1234.56, grouping=True)
'$1,234.56'
Key Features
- Sets and retrieves locale settings
- Formats numbers, dates, and currencies according to locale
- Accesses locale-specific data, such as decimal points and thousands separators
Frequently Used Classes and Functions
Object | Type | Description |
---|---|---|
locale.setlocale() |
Function | Sets the current locale |
locale.getlocale() |
Function | Gets the current setting for the locale |
locale.currency() |
Function | Formats currency according to the current locale |
locale.localeconv() |
Function | Retrieves a mapping of locale-specific conventions |
Examples
Setting and retrieving the current locale:
>>> import locale
>>> locale.setlocale(locale.LC_ALL, "fr_FR.UTF-8")
'fr_FR.UTF-8'
>>> locale.getlocale(locale.LC_ALL)
('fr_FR', 'UTF-8')
Note: The desired locale (fr_FR.UTF-8
) must be installed and available on your system for this code to work. Otherwise, locale.setlocale()
will raise an error.
Formatting a number as currency according to the current locale:
>>> locale.currency(1234.56)
'1234,56 €'
Common Use Cases
- Formatting numbers and currencies in a locale-sensitive manner
- Adapting applications to display content in different regional settings
- Converting between different locale data formats
Real-World Example
Imagine you need to display product prices in the user’s local currency format. Here’s how you might use the locale
module to achieve that:
>>> import locale
>>> locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
'en_US.UTF-8'
>>> prices = [19.99, 5.49, 3.75]
>>> formatted_prices = [
... locale.currency(price, grouping=True) for price in prices
... ]
>>> formatted_prices
['$19.99', '$5.49', '$3.75']
In this example, you use the locale
module to format a list of product prices according to the user’s local currency format, making the application more user-friendly and regionally appropriate.
Related Resources
Tutorial
Using Python datetime to Work With Dates and Times
Have you ever wondered about working with dates and times in Python? In this tutorial, you'll learn all about the built-in Python datetime library. You'll also learn about how to manage time zones and daylight saving time, and how to do accurate arithmetic on dates and times.
For additional information on related topics, take a look at the following resources:
- Using Python's datetime Module (Course)
By Leodanis Pozo Ramos • Updated July 11, 2025