On this page
  1. locale
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Opting Into the User's Environment Locale
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects
  10. Constants & Attributes

locale

Prev: linecache | Up: stdlib_module | Next: logging
Rel: wave, colorsys, gettext, turtle, turtledemo
Ref: docs.python.org — locale
Tags: #public #python3 #stdlib


Import

import locale

Overview

Interface to the POSIX/C locale database for culture-aware number formatting, currency symbols, decimal separators, and locale-aware string collation (setlocale(), format_string(), currency(), strxfrm()). Reach for locale when CLI tools must respect the user's OS regional settings.

Quick Start

import locale

# Query the current numeric locale without mutating global state
conv = locale.localeconv()
assert "decimal_point" in conv

# Format numbers according to the active locale (default is POSIX "C")
formatted = locale.format_string("%.2f", 1234.5, grouping=True)
assert formatted.endswith(".50") or formatted.endswith(",50")

Implementation Walkthrough

1. Opting Into the User's Environment Locale

Python starts in the minimal "C" locale regardless of LANG/LC_ALL. Call setlocale(LC_ALL, "") once at application startup to adopt the user's OS locale, then sort with locale.strxfrm:

import locale

# In a CLI main():
# locale.setlocale(locale.LC_ALL, "")
words = ["banana", "Apple", "cherry"]
sorted_words = sorted(words, key=locale.strxfrm)
assert len(sorted_words) == 3

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes