On this page
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
- Process-global and NOT thread-safe:
locale.setlocale()mutates C-library global state for the entire process. Never call it inside libraries or multi-threaded web request handlers; useBabelfor per-request localization. - Locale names vary by OS:
"en_US.UTF-8"on macOS/Linux vs."English_United States.1252"on Windows, and minimal Docker containers often only ship"C"and"C.UTF-8"(raisinglocale.Errorfor others). - Avoid
locale.getdefaultlocale(): Deprecated and removed in newer Python 3 versions; uselocale.getlocale()orlocale.getencoding()instead.
Common Functions
- locale.atof() —
atof(string, func=<class 'float'>)— Parses a string as a float according to the locale settings. - locale.atoi() —
atoi(string)— Converts a string to an integer according to the locale settings. - locale.currency() —
currency(val, symbol=True, grouping=False, international=False)— Formats val according to the currency settings in the current locale. - locale.format_string() —
format_string(f, val, grouping=False, monetary=False)— Formats a string in the same way that the % formatting would use, but takes the current locale into account. - locale.getdefaultlocale() —
getdefaultlocale(envvars=('LC_ALL', 'LC_CTYPE', 'LANG', 'LANGUAGE'))— Tries to determine the default locale settings and returns them as tuple (language code, encoding). - locale.getencoding() —
getencoding()— Get the current locale encoding. - locale.getlocale() —
getlocale(category=2)— Returns the current setting for the given locale category as tuple (language code, encoding). - locale.getpreferredencoding() —
getpreferredencoding(do_setlocale=True)— Return the charset that the user is likely using, according to the system configuration. - locale.localeconv() —
localeconv()— Returns numeric and monetary locale-specific parameters. - locale.normalize() —
normalize(localename)— Returns a normalized locale code for the given locale name. - locale.setlocale() —
setlocale(category, locale=None)— Set the locale for the given category. The locale can be a string, an iterable of two strings (language code and encoding), or None. - locale.str() —
str(val)— Convert float to string, taking the locale into account. - locale.strcoll() —
strcoll(os1, os2, /)— Compares two strings according to the locale. - locale.strxfrm() —
strxfrm(string, /)— Return a string that can be used as a key for locale-aware comparisons.
Classes & Objects
- locale.Error —
locale.Errorclass. (Methods:.add_note(),.with_traceback())
Constants & Attributes
locale.CHAR_MAX(int) =127locale.LC_ALL(int) =0locale.LC_COLLATE(int) =1locale.LC_CTYPE(int) =2locale.LC_MESSAGES(int) =6locale.LC_MONETARY(int) =3locale.LC_NUMERIC(int) =4locale.LC_TIME(int) =5
Linked from
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/cmd
- tuts/python3/stdlib_module/colorsys
- tuts/python3/stdlib_module/gettext
- tuts/python3/stdlib_module/idlelib
- tuts/python3/stdlib_module/linecache
- tuts/python3/stdlib_module/locale/atof
- tuts/python3/stdlib_module/locale/atoi
- tuts/python3/stdlib_module/locale/currency
- tuts/python3/stdlib_module/locale/Error
- tuts/python3/stdlib_module/locale/format_string
- tuts/python3/stdlib_module/locale/getdefaultlocale
- tuts/python3/stdlib_module/locale/getencoding
- tuts/python3/stdlib_module/locale/getlocale
- tuts/python3/stdlib_module/locale/getpreferredencoding
- tuts/python3/stdlib_module/locale/localeconv
- tuts/python3/stdlib_module/locale/normalize
- tuts/python3/stdlib_module/locale/setlocale
- tuts/python3/stdlib_module/locale/str
- tuts/python3/stdlib_module/locale/strcoll
- tuts/python3/stdlib_module/locale/strxfrm
- tuts/python3/stdlib_module/logging
- tuts/python3/stdlib_module/shlex
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/tkinter
- tuts/python3/stdlib_module/turtle
- tuts/python3/stdlib_module/turtledemo
- tuts/python3/stdlib_module/wave
Related notes
- tuts/python3/stdlib_module/colorsys Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/gettext Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/linecache Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/locale/atof Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/locale/atoi Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/locale/currency Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/locale/Error Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/locale/format_string Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/locale/getdefaultlocale Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/locale/getencoding Linked here; links to this page; shared tags: #stdlib