The locale Module

The locale module, as shown in Example 8-1, provides an interface to C's localization functions. It also provides functions to convert between numbers and strings based on the current locale. (Functions like int and float, as well as the numeric conversion functions in string, are not affected by the current locale.)

Example 8-1. Using the locale Module for Data Formatting

File: locale-example-1.py import locale print "locale", "=>", locale.setlocale(locale.LC_ALL, "") # integer formatting value = 4711 print locale.format("%d", value, 1), "==", print locale.atoi(locale.format("%d", value, 1)) # floating point value = 47.11 print locale.format("%f", value, 1), "==", print locale.atof(locale.format("%f", value, 1)) info = locale.localeconv() print info["int_curr_symbol"] locale => Swedish_Sweden.1252 4,711 == 4711 47,110000 == 47.11 SEK

Example 8-2 shows how you can use the locale module to get the platform locale.

Example 8-2. Using the locale Module to Get the Platform Locale

File: locale-example-2.py import locale language, encoding = locale.getdefaultlocale() print "language", language print "encoding", encoding language sv_SE encoding cp1252

Категории