locale — Internationalization services¶
The locale module opens access to the POSIX locale database and functionality. The POSIX locale mechanism allows programmers to deal with certain cultural issues in an application, without requiring the programmer to know all the specifics of each country where the software is executed.
The locale module is implemented on top of the _locale module, which in turn uses an ANSI C locale implementation if available.
The locale module defines the following exception and functions:
exception locale. Error ¶
Exception raised when the locale passed to setlocale() is not recognized.
locale. setlocale ( category , locale = None ) ¶
If locale is given and not None , setlocale() modifies the locale setting for the category. The available categories are listed in the data description below. locale may be a string, or an iterable of two strings (language code and encoding). If it’s an iterable, it’s converted to a locale name using the locale aliasing engine. An empty string specifies the user’s default settings. If the modification of the locale fails, the exception Error is raised. If successful, the new locale setting is returned.
If locale is omitted or None , the current setting for category is returned.
setlocale() is not thread-safe on most systems. Applications typically start with a call of
This sets the locale for all categories to the user’s default setting (typically specified in the LANG environment variable). If the locale is not changed thereafter, using multithreading should not cause problems.
Returns the database of the local conventions as a dictionary. This dictionary has the following strings as keys:
Decimal point character.
Sequence of numbers specifying which relative positions the ‘thousands_sep’ is expected. If the sequence is terminated with CHAR_MAX , no further grouping is performed. If the sequence terminates with a 0 , the last group size is repeatedly used.
Character used between groups.
International currency symbol.
Local currency symbol.
Whether the currency symbol precedes the value (for positive resp. negative values).
Whether the currency symbol is separated from the value by a space (for positive resp. negative values).
Decimal point used for monetary values.
Number of fractional digits used in local formatting of monetary values.
Number of fractional digits used in international formatting of monetary values.
Group separator used for monetary values.
Equivalent to ‘grouping’ , used for monetary values.
Symbol used to annotate a positive monetary value.
Symbol used to annotate a negative monetary value.
The position of the sign (for positive resp. negative values), see below.
All numeric values can be set to CHAR_MAX to indicate that there is no value specified in this locale.
The possible values for ‘p_sign_posn’ and ‘n_sign_posn’ are given below.
Currency and value are surrounded by parentheses.
The sign should precede the value and currency symbol.
The sign should follow the value and currency symbol.
The sign should immediately precede the value.
The sign should immediately follow the value.
Nothing is specified in this locale.
The function temporarily sets the LC_CTYPE locale to the LC_NUMERIC locale or the LC_MONETARY locale if locales are different and numeric or monetary strings are non-ASCII. This temporary change affects other threads.
Changed in version 3.7: The function now temporarily sets the LC_CTYPE locale to the LC_NUMERIC locale in some cases.
Return some locale-specific information as a string. This function is not available on all systems, and the set of possible options might also vary across platforms. The possible argument values are numbers, for which symbolic constants are available in the locale module.
The nl_langinfo() function accepts one of the following keys. Most descriptions are taken from the corresponding description in the GNU C library.
Get a string with the name of the character encoding used in the selected locale.
Get a string that can be used as a format string for time.strftime() to represent date and time in a locale-specific way.
Get a string that can be used as a format string for time.strftime() to represent a date in a locale-specific way.
Get a string that can be used as a format string for time.strftime() to represent a time in a locale-specific way.
Get a format string for time.strftime() to represent time in the am/pm format.
Get the name of the n-th day of the week.
This follows the US convention of DAY_1 being Sunday, not the international convention (ISO 8601) that Monday is the first day of the week.
Get the abbreviated name of the n-th day of the week.
Get the name of the n-th month.
Get the abbreviated name of the n-th month.
Get the radix character (decimal dot, decimal comma, etc.).
Get the separator character for thousands (groups of three digits).
Get a regular expression that can be used with the regex function to recognize a positive response to a yes/no question.
Get a regular expression that can be used with the regex(3) function to recognize a negative response to a yes/no question.
The regular expressions for YESEXPR and NOEXPR use syntax suitable for the regex() function from the C library, which might differ from the syntax used in re .
Get the currency symbol, preceded by “-” if the symbol should appear before the value, “+” if the symbol should appear after the value, or “.” if the symbol should replace the radix character.
Get a string that represents the era used in the current locale.
Most locales do not define this value. An example of a locale which does define this value is the Japanese one. In Japan, the traditional representation of dates includes the name of the era corresponding to the then-emperor’s reign.
Normally it should not be necessary to use this value directly. Specifying the E modifier in their format strings causes the time.strftime() function to use this information. The format of the returned string is not specified, and therefore you should not assume knowledge of it on different systems.
Get a format string for time.strftime() to represent date and time in a locale-specific era-based way.
Get a format string for time.strftime() to represent a date in a locale-specific era-based way.
Get a format string for time.strftime() to represent a time in a locale-specific era-based way.
Get a representation of up to 100 values used to represent the values 0 to 99.
locale. getdefaultlocale ( [ envvars ] ) ¶
Tries to determine the default locale settings and returns them as a tuple of the form (language code, encoding) .
According to POSIX, a program which has not called setlocale(LC_ALL, ») runs using the portable ‘C’ locale. Calling setlocale(LC_ALL, ») lets it use the default locale as defined by the LANG variable. Since we do not want to interfere with the current locale setting we thus emulate the behavior in the way described above.
To maintain compatibility with other platforms, not only the LANG variable is tested, but a list of variables given as envvars parameter. The first found to be defined will be used. envvars defaults to the search path used in GNU gettext; it must always contain the variable name ‘LANG’ . The GNU gettext search path contains ‘LC_ALL’ , ‘LC_CTYPE’ , ‘LANG’ and ‘LANGUAGE’ , in that order.
Except for the code ‘C’ , the language code corresponds to RFC 1766. language code and encoding may be None if their values cannot be determined.
Deprecated since version 3.11, will be removed in version 3.13.
Returns the current setting for the given locale category as sequence containing language code, encoding. category may be one of the LC_* values except LC_ALL . It defaults to LC_CTYPE .
Except for the code ‘C’ , the language code corresponds to RFC 1766. language code and encoding may be None if their values cannot be determined.
locale. getpreferredencoding ( do_setlocale = True ) ¶
Return the locale encoding used for text data, according to user preferences. User preferences are expressed differently on different systems, and might not be available programmatically on some systems, so this function only returns a guess.
On some systems, it is necessary to invoke setlocale() to obtain the user preferences, so this function is not thread-safe. If invoking setlocale is not necessary or desired, do_setlocale should be set to False .
On Android or if the Python UTF-8 Mode is enabled, always return ‘utf-8’ , the locale encoding and the do_setlocale argument are ignored.
Changed in version 3.7: The function now always returns "utf-8" on Android or if the Python UTF-8 Mode is enabled.
On Android and VxWorks, return "utf-8" .
On Unix, return the encoding of the current LC_CTYPE locale. Return "utf-8" if nl_langinfo(CODESET) returns an empty string: for example, if the current LC_CTYPE locale is not supported.
On Windows, return the ANSI code page.
This function is similar to getpreferredencoding(False) except this function ignores the Python UTF-8 Mode .
New in version 3.11.
Returns a normalized locale code for the given locale name. The returned locale code is formatted for use with setlocale() . If normalization fails, the original name is returned unchanged.
If the given encoding is not known, the function defaults to the default encoding for the locale code just like setlocale() .
locale. resetlocale ( category = LC_ALL ) ¶
Sets the locale for category to the default setting.
The default setting is determined by calling getdefaultlocale() . category defaults to LC_ALL .
Deprecated since version 3.11, will be removed in version 3.13.
Compares two strings according to the current LC_COLLATE setting. As any other compare function, returns a negative, or a positive value, or 0 , depending on whether string1 collates before or after string2 or is equal to it.
locale. strxfrm ( string ) ¶
Transforms a string to one that can be used in locale-aware comparisons. For example, strxfrm(s1) < strxfrm(s2) is equivalent to strcoll(s1, s2) < 0 . This function can be used when the same string is compared repeatedly, e.g. when collating a sequence of strings.
locale. format_string ( format , val , grouping = False , monetary = False ) ¶
Formats a number val according to the current LC_NUMERIC setting. The format follows the conventions of the % operator. For floating point values, the decimal point is modified if appropriate. If grouping is True , also takes the grouping into account.
If monetary is true, the conversion uses monetary thousands separator and grouping strings.
Processes formatting specifiers as in format % val , but takes the current locale settings into account.
Changed in version 3.7: The monetary keyword parameter was added.
Please note that this function works like format_string() but will only work for exactly one %char specifier. For example, ‘%f’ and ‘%.0f’ are both valid specifiers, but ‘%f KiB’ is not.
For whole format strings, use format_string() .
Deprecated since version 3.7: Use format_string() instead.
Formats a number val according to the current LC_MONETARY settings.
The returned string includes the currency symbol if symbol is true, which is the default. If grouping is True (which is not the default), grouping is done with the value. If international is True (which is not the default), the international currency symbol is used.
This function will not work with the ‘C’ locale, so you have to set a locale via setlocale() first.
Formats a floating point number using the same format as the built-in function str(float) , but takes the decimal point into account.
locale. delocalize ( string ) ¶
Converts a string into a normalized number string, following the LC_NUMERIC settings.
New in version 3.5.
Converts a normalized number string into a formatted string following the LC_NUMERIC settings.
New in version 3.10.
Converts a string to a number, following the LC_NUMERIC settings, by calling func on the result of calling delocalize() on string.
locale. atoi ( string ) ¶
Converts a string to an integer, following the LC_NUMERIC conventions.
Locale category for the character type functions. Depending on the settings of this category, the functions of module string dealing with case change their behaviour.
Locale category for sorting strings. The functions strcoll() and strxfrm() of the locale module are affected.
Locale category for the formatting of time. The function time.strftime() follows these conventions.
Locale category for formatting of monetary values. The available options are available from the localeconv() function.
Locale category for message display. Python currently does not support application specific locale-aware messages. Messages displayed by the operating system, like those returned by os.strerror() might be affected by this category.
This value may not be available on operating systems not conforming to the POSIX standard, most notably Windows.
Locale category for formatting numbers. The functions format() , atoi() , atof() and str() of the locale module are affected by that category. All other numeric formatting operations are not affected.
Combination of all locale settings. If this flag is used when the locale is changed, setting the locale for all categories is attempted. If that fails for any category, no category is changed at all. When the locale is retrieved using this flag, a string indicating the setting for all categories is returned. This string can be later used to restore the settings.
This is a symbolic constant used for different values returned by localeconv() .
Background, details, hints, tips and caveats¶
The C standard defines the locale as a program-wide property that may be relatively expensive to change. On top of that, some implementations are broken in such a way that frequent locale changes may cause core dumps. This makes the locale somewhat painful to use correctly.
Initially, when a program is started, the locale is the C locale, no matter what the user’s preferred locale is. There is one exception: the LC_CTYPE category is changed at startup to set the current locale encoding to the user’s preferred locale encoding. The program must explicitly say that it wants the user’s preferred locale settings for other categories by calling setlocale(LC_ALL, ») .
It is generally a bad idea to call setlocale() in some library routine, since as a side effect it affects the entire program. Saving and restoring it is almost as bad: it is expensive and affects other threads that happen to run before the settings have been restored.
If, when coding a module for general use, you need a locale independent version of an operation that is affected by the locale (such as certain formats used with time.strftime() ), you will have to find a way to do it without using the standard library routine. Even better is convincing yourself that using locale settings is okay. Only as a last resort should you document that your module is not compatible with non- C locale settings.
The only way to perform numeric operations according to the locale is to use the special functions defined by this module: atof() , atoi() , format() , str() .
There is no way to perform case conversions and character classifications according to the locale. For (Unicode) text strings these are done according to the character value only, while for byte strings, the conversions and classifications are done according to the ASCII value of the byte, and bytes whose high bit is set (i.e., non-ASCII bytes) are never converted or considered part of a character class such as letter or whitespace.
For extension writers and programs that embed Python¶
Extension modules should never call setlocale() , except to find out what the current locale is. But since the return value can only be used portably to restore it, that is not very useful (except perhaps to find out whether or not the locale is C ).
When Python code uses the locale module to change the locale, this also affects the embedding application. If the embedding application doesn’t want this to happen, it should remove the _locale extension module (which does all the work) from the table of built-in modules in the config.c file, and make sure that the _locale module is not accessible as a shared library.
Access to message catalogs¶
The locale module exposes the C library’s gettext interface on systems that provide this interface. It consists of the functions gettext() , dgettext() , dcgettext() , textdomain() , bindtextdomain() , and bind_textdomain_codeset() . These are similar to the same functions in the gettext module, but use the C library’s binary format for message catalogs, and the C library’s search algorithms for locating message catalogs.
Python applications should normally find no need to invoke these functions, and should use gettext instead. A known exception to this rule are applications that link with additional C libraries which internally invoke gettext() or dcgettext() . For these applications, it may be necessary to bind the text domain, so that the libraries can properly locate their message catalogs.
Функция setlocale() модуля locale в Python
Функция setlocale() модуля locale изменяет настройку языкового стандарта для категории category если указан языковой стандарт locale . В случае успеха смены локали возвращается новая настройка локали. Если языковой стандарт locale опущен или отсутствует, возвращается текущий параметр категории category .
Доступные категории category перечислены в разделе "Категории локали модуля locale ."
Аргумент locale может быть строкой или кортежем из двух строк ('код языка', 'кодировка') :
- Если это итеративный код, он преобразуется в имя локали с помощью механизма псевдонимов локалей.
- Пустая строка locale='' указывает настройки пользователя по умолчанию.
- Если изменение языкового стандарта завершается неудачей, возникает ошибка Error.
Функция locale.setlocale() не является потокобезопасной на большинстве систем. обычно приложения начинают работу с вызова этой функции для проверки или корректировки региональных настроек.
Функция устанавливает языковой стандарт для всех категорий в соответствии с настройками пользователя по умолчанию и обычно указывается в переменной среды LANG . Если после этого языковой стандарт не изменился, использование многопоточности не должно вызывать проблем.
Примеры использования:
Посмотрим как зависят региональные настройки от установки локали в Python.
Как поменять язык в питоне на русский
The locale module opens access to the POSIX locale database and functionality. The POSIX locale mechanism allows programmers to deal with certain cultural issues in an application, without requiring the programmer to know all the specifics of each country where the software is executed.
The locale module is implemented on top of the _locale module, which in turn uses an ANSI C locale implementation if available.
The locale module defines the following exception and functions:
exception locale. Error ¶
Exception raised when the locale passed to setlocale() is not recognized.
locale. setlocale ( category , locale = None ) ¶
If locale is given and not None , setlocale() modifies the locale setting for the category. The available categories are listed in the data description below. locale may be a string, or an iterable of two strings (language code and encoding). If it’s an iterable, it’s converted to a locale name using the locale aliasing engine. An empty string specifies the user’s default settings. If the modification of the locale fails, the exception Error is raised. If successful, the new locale setting is returned.
If locale is omitted or None , the current setting for category is returned.
setlocale() is not thread-safe on most systems. Applications typically start with a call of
This sets the locale for all categories to the user’s default setting (typically specified in the LANG environment variable). If the locale is not changed thereafter, using multithreading should not cause problems.
Returns the database of the local conventions as a dictionary. This dictionary has the following strings as keys:
Decimal point character.
Sequence of numbers specifying which relative positions the ‘thousands_sep’ is expected. If the sequence is terminated with CHAR_MAX , no further grouping is performed. If the sequence terminates with a 0 , the last group size is repeatedly used.
Character used between groups.
International currency symbol.
Local currency symbol.
Whether the currency symbol precedes the value (for positive resp. negative values).
Whether the currency symbol is separated from the value by a space (for positive resp. negative values).
Decimal point used for monetary values.
Number of fractional digits used in local formatting of monetary values.
Number of fractional digits used in international formatting of monetary values.
Group separator used for monetary values.
Equivalent to ‘grouping’ , used for monetary values.
Symbol used to annotate a positive monetary value.
Symbol used to annotate a negative monetary value.
The position of the sign (for positive resp. negative values), see below.
All numeric values can be set to CHAR_MAX to indicate that there is no value specified in this locale.
The possible values for ‘p_sign_posn’ and ‘n_sign_posn’ are given below.
Currency and value are surrounded by parentheses.
The sign should precede the value and currency symbol.
The sign should follow the value and currency symbol.
The sign should immediately precede the value.
The sign should immediately follow the value.
Nothing is specified in this locale.
The function temporarily sets the LC_CTYPE locale to the LC_NUMERIC locale or the LC_MONETARY locale if locales are different and numeric or monetary strings are non-ASCII. This temporary change affects other threads.
Changed in version 3.7: The function now temporarily sets the LC_CTYPE locale to the LC_NUMERIC locale in some cases.
Return some locale-specific information as a string. This function is not available on all systems, and the set of possible options might also vary across platforms. The possible argument values are numbers, for which symbolic constants are available in the locale module.
The nl_langinfo() function accepts one of the following keys. Most descriptions are taken from the corresponding description in the GNU C library.
Get a string with the name of the character encoding used in the selected locale.
Get a string that can be used as a format string for time.strftime() to represent date and time in a locale-specific way.
Get a string that can be used as a format string for time.strftime() to represent a date in a locale-specific way.
Get a string that can be used as a format string for time.strftime() to represent a time in a locale-specific way.
Get a format string for time.strftime() to represent time in the am/pm format.
Get the name of the n-th day of the week.
This follows the US convention of DAY_1 being Sunday, not the international convention (ISO 8601) that Monday is the first day of the week.
Get the abbreviated name of the n-th day of the week.
Get the name of the n-th month.
Get the abbreviated name of the n-th month.
Get the radix character (decimal dot, decimal comma, etc.).
Get the separator character for thousands (groups of three digits).
Get a regular expression that can be used with the regex function to recognize a positive response to a yes/no question.
Get a regular expression that can be used with the regex(3) function to recognize a negative response to a yes/no question.
The regular expressions for YESEXPR and NOEXPR use syntax suitable for the regex() function from the C library, which might differ from the syntax used in re .
Get the currency symbol, preceded by “-” if the symbol should appear before the value, “+” if the symbol should appear after the value, or “.” if the symbol should replace the radix character.
Get a string that represents the era used in the current locale.
Most locales do not define this value. An example of a locale which does define this value is the Japanese one. In Japan, the traditional representation of dates includes the name of the era corresponding to the then-emperor’s reign.
Normally it should not be necessary to use this value directly. Specifying the E modifier in their format strings causes the time.strftime() function to use this information. The format of the returned string is not specified, and therefore you should not assume knowledge of it on different systems.
Get a format string for time.strftime() to represent date and time in a locale-specific era-based way.
Get a format string for time.strftime() to represent a date in a locale-specific era-based way.
Get a format string for time.strftime() to represent a time in a locale-specific era-based way.
Get a representation of up to 100 values used to represent the values 0 to 99.
locale. getdefaultlocale ( [ envvars ] ) ¶
Tries to determine the default locale settings and returns them as a tuple of the form (language code, encoding) .
According to POSIX, a program which has not called setlocale(LC_ALL, ») runs using the portable ‘C’ locale. Calling setlocale(LC_ALL, ») lets it use the default locale as defined by the LANG variable. Since we do not want to interfere with the current locale setting we thus emulate the behavior in the way described above.
To maintain compatibility with other platforms, not only the LANG variable is tested, but a list of variables given as envvars parameter. The first found to be defined will be used. envvars defaults to the search path used in GNU gettext; it must always contain the variable name ‘LANG’ . The GNU gettext search path contains ‘LC_ALL’ , ‘LC_CTYPE’ , ‘LANG’ and ‘LANGUAGE’ , in that order.
Except for the code ‘C’ , the language code corresponds to RFC 1766. language code and encoding may be None if their values cannot be determined.
Deprecated since version 3.11, will be removed in version 3.13.
Returns the current setting for the given locale category as sequence containing language code, encoding. category may be one of the LC_* values except LC_ALL . It defaults to LC_CTYPE .
Except for the code ‘C’ , the language code corresponds to RFC 1766. language code and encoding may be None if their values cannot be determined.
locale. getpreferredencoding ( do_setlocale = True ) ¶
Return the locale encoding used for text data, according to user preferences. User preferences are expressed differently on different systems, and might not be available programmatically on some systems, so this function only returns a guess.
On some systems, it is necessary to invoke setlocale() to obtain the user preferences, so this function is not thread-safe. If invoking setlocale is not necessary or desired, do_setlocale should be set to False .
On Android or if the Python UTF-8 Mode is enabled, always return ‘utf-8’ , the locale encoding and the do_setlocale argument are ignored.
Changed in version 3.7: The function now always returns "utf-8" on Android or if the Python UTF-8 Mode is enabled.
On Android and VxWorks, return "utf-8" .
On Unix, return the encoding of the current LC_CTYPE locale. Return "utf-8" if nl_langinfo(CODESET) returns an empty string: for example, if the current LC_CTYPE locale is not supported.
On Windows, return the ANSI code page.
This function is similar to getpreferredencoding(False) except this function ignores the Python UTF-8 Mode .
New in version 3.11.
Returns a normalized locale code for the given locale name. The returned locale code is formatted for use with setlocale() . If normalization fails, the original name is returned unchanged.
If the given encoding is not known, the function defaults to the default encoding for the locale code just like setlocale() .
locale. resetlocale ( category = LC_ALL ) ¶
Sets the locale for category to the default setting.
The default setting is determined by calling getdefaultlocale() . category defaults to LC_ALL .
Deprecated since version 3.11, will be removed in version 3.13.
Compares two strings according to the current LC_COLLATE setting. As any other compare function, returns a negative, or a positive value, or 0 , depending on whether string1 collates before or after string2 or is equal to it.
locale. strxfrm ( string ) ¶
Transforms a string to one that can be used in locale-aware comparisons. For example, strxfrm(s1) < strxfrm(s2) is equivalent to strcoll(s1, s2) < 0 . This function can be used when the same string is compared repeatedly, e.g. when collating a sequence of strings.
locale. format_string ( format , val , grouping = False , monetary = False ) ¶
Formats a number val according to the current LC_NUMERIC setting. The format follows the conventions of the % operator. For floating point values, the decimal point is modified if appropriate. If grouping is True , also takes the grouping into account.
If monetary is true, the conversion uses monetary thousands separator and grouping strings.
Processes formatting specifiers as in format % val , but takes the current locale settings into account.
Changed in version 3.7: The monetary keyword parameter was added.
Please note that this function works like format_string() but will only work for exactly one %char specifier. For example, ‘%f’ and ‘%.0f’ are both valid specifiers, but ‘%f KiB’ is not.
For whole format strings, use format_string() .
Deprecated since version 3.7: Use format_string() instead.
Formats a number val according to the current LC_MONETARY settings.
The returned string includes the currency symbol if symbol is true, which is the default. If grouping is True (which is not the default), grouping is done with the value. If international is True (which is not the default), the international currency symbol is used.
This function will not work with the ‘C’ locale, so you have to set a locale via setlocale() first.
Formats a floating point number using the same format as the built-in function str(float) , but takes the decimal point into account.
locale. delocalize ( string ) ¶
Converts a string into a normalized number string, following the LC_NUMERIC settings.
New in version 3.5.
Converts a normalized number string into a formatted string following the LC_NUMERIC settings.
New in version 3.10.
Converts a string to a number, following the LC_NUMERIC settings, by calling func on the result of calling delocalize() on string.
locale. atoi ( string ) ¶
Converts a string to an integer, following the LC_NUMERIC conventions.
Locale category for the character type functions. Depending on the settings of this category, the functions of module string dealing with case change their behaviour.
Locale category for sorting strings. The functions strcoll() and strxfrm() of the locale module are affected.
Locale category for the formatting of time. The function time.strftime() follows these conventions.
Locale category for formatting of monetary values. The available options are available from the localeconv() function.
Locale category for message display. Python currently does not support application specific locale-aware messages. Messages displayed by the operating system, like those returned by os.strerror() might be affected by this category.
This value may not be available on operating systems not conforming to the POSIX standard, most notably Windows.
Locale category for formatting numbers. The functions format() , atoi() , atof() and str() of the locale module are affected by that category. All other numeric formatting operations are not affected.
Combination of all locale settings. If this flag is used when the locale is changed, setting the locale for all categories is attempted. If that fails for any category, no category is changed at all. When the locale is retrieved using this flag, a string indicating the setting for all categories is returned. This string can be later used to restore the settings.
This is a symbolic constant used for different values returned by localeconv() .
Background, details, hints, tips and caveats¶
The C standard defines the locale as a program-wide property that may be relatively expensive to change. On top of that, some implementations are broken in such a way that frequent locale changes may cause core dumps. This makes the locale somewhat painful to use correctly.
Initially, when a program is started, the locale is the C locale, no matter what the user’s preferred locale is. There is one exception: the LC_CTYPE category is changed at startup to set the current locale encoding to the user’s preferred locale encoding. The program must explicitly say that it wants the user’s preferred locale settings for other categories by calling setlocale(LC_ALL, ») .
It is generally a bad idea to call setlocale() in some library routine, since as a side effect it affects the entire program. Saving and restoring it is almost as bad: it is expensive and affects other threads that happen to run before the settings have been restored.
If, when coding a module for general use, you need a locale independent version of an operation that is affected by the locale (such as certain formats used with time.strftime() ), you will have to find a way to do it without using the standard library routine. Even better is convincing yourself that using locale settings is okay. Only as a last resort should you document that your module is not compatible with non- C locale settings.
The only way to perform numeric operations according to the locale is to use the special functions defined by this module: atof() , atoi() , format() , str() .
There is no way to perform case conversions and character classifications according to the locale. For (Unicode) text strings these are done according to the character value only, while for byte strings, the conversions and classifications are done according to the ASCII value of the byte, and bytes whose high bit is set (i.e., non-ASCII bytes) are never converted or considered part of a character class such as letter or whitespace.
For extension writers and programs that embed Python¶
Extension modules should never call setlocale() , except to find out what the current locale is. But since the return value can only be used portably to restore it, that is not very useful (except perhaps to find out whether or not the locale is C ).
When Python code uses the locale module to change the locale, this also affects the embedding application. If the embedding application doesn’t want this to happen, it should remove the _locale extension module (which does all the work) from the table of built-in modules in the config.c file, and make sure that the _locale module is not accessible as a shared library.
Access to message catalogs¶
The locale module exposes the C library’s gettext interface on systems that provide this interface. It consists of the functions gettext() , dgettext() , dcgettext() , textdomain() , bindtextdomain() , and bind_textdomain_codeset() . These are similar to the same functions in the gettext module, but use the C library’s binary format for message catalogs, and the C library’s search algorithms for locating message catalogs.
Python applications should normally find no need to invoke these functions, and should use gettext instead. A known exception to this rule are applications that link with additional C libraries which internally invoke gettext() or dcgettext() . For these applications, it may be necessary to bind the text domain, so that the libraries can properly locate their message catalogs.
A Beginner’s Guide to Python’s locale Module
![]()
Python’s locale module is part of the standard library for internationalization (i18n) and localization (l10n) in Python. The locale module allows developers to deal with certain cultural issues in their application. Thereby, they need not know all the specifics of the location or language where the software is used. Let’s explore in great detail the basic concept of Python’s locale module.
The Basics of Python’s locale module
Import and Initialization
Based on the official documentation, the locale module is implemented on top of the _locale module. It uses an ANSI C locale implementation if available. A normal application typically starts with the following code to set the locale:
The first parameter represents the locale category while the second parameter modifies the locale setting for the category. It will use the current setting for the category if the second parameter is not present or None. On the other hand, an empty string will use the user’s default setting.
In the following example, the locale is set to German (de_DE).
Most of the time, it uses the Language Code Identifier (LCID) Reference, as stated in the following link (replace the hyphen in the language tags with an underscore). For example, de-DE should be stated as de_DE. However, older OS versions might accept the locale in a different format, as shown below:
List of Available Locales
The recommended method is to test out the standard Language Code Identifier Reference first. If you encountered an error, the next step is to print out the full list of the available locales in your machine.
Get an Existing Locale
You can get the string for the existing locale with the following code:
Information on an Existing Locale
Calling the built-in localeconv() function will provide you with detailed information on the current locale. Run the following code to visualize it:
Here an example output for en_SG (English/Singapore):
Check out the official documentation for more information on the keys and their respective meaning.
Format and Parse Number
The locale module provides two specialized functions to parse a string into a number, based on the current locale:
- atof (convert a string to a floating point number), and
- atoi (convert a string to integer).
This is extremely useful for parsing a string that contains a comma or dot, as different locales interpret it differently. For example:
- 32,824 is 32824.00 for en_SG (English/Singapore),
- 32,824 is 32.824 for de_DE (German).
On top of that, you can use the format_string() function to format a number according to your preferences. The following code snippet is based on the de_DE locale:
You can set a grouping parameter for the format_string() function, which accepts a boolean.
- grouping (if set to True, it takes grouping into account; otherwise, it is False by default).
Format Currency
Furthermore, you can utilize the built-in currency() function to format any input number. The end result comes with the currency symbol or text. Let us have a look at the following example for en_SG:
Apart from the number input, the currency() function also accepts three additional parameters:
- symbol (if set to True, the returned string includes the currency symbol; the default value is True),
- grouping (if set to True, the grouping is done with the value; the default value is False),
- international (if set to True, the international currency symbol is used; the default value is False).
Formatting Date and Time
Other than that, the datetime module helps in formatting date and time, based on the locale that you have set. The easiest way is to rely on the strftime() function. It converts an object to a string according to a given format. It can be a date, time, or datetime object. Let’s have a look at the following list of common format codes
- %A — weekday as locale’s full name,
- %b — month as locale’s abbreviated name,
- %m — month as a zero-padded decimal number,
- %Y — year with century as a decimal number,
- %H — hour (24-hour clock) as a zero-padded decimal number,
- %I — hour (12-hour clock) as a zero-padded decimal number (capital “i”),
- %p — locale’s equivalent of either AM or PM,
- %M — minute as a zero-padded decimal number,
- %S — second as a zero-padded decimal number,
- %Z — time zone name (empty string if the object is naive).
You can find the full list of format codes in the following link.
Simply define the format in a string, and use it as the input parameter when calling the strftime() function. Check out the following example displaying the current date and time.
In addition, you can display just the date component for a specific RSVP event as follows:
If a value is stored as a timestamp in your database, you can easily convert it to a datetime object:
%I (capital i) represents a 12-hour clock as a zero-padded decimal number. You can remove the leading zero by adding a hyphen or pound sign based on the operating system of your machine. For example,
- Linux, OS X: %-I
- Windows, Cygwin: %#I
Besides, you can highlight the timezone as long as the datetime object contains the optimal timezone information. We call this an aware datetime object. In contrast, a naive datetime object does not contain enough information to unambiguously locate itself in relation to other datetime objects. You can easily identify if a datetime object is aware or naive by printing it out.
For your information, you can easily construct and define a timezone in a datetime object by using datetime.timezone. Let us have a look at the following example of creating instances of current datetime based on different timezones.
%Z will return an empty string, called by a naive datetime object.
Best Practice
Based on the official documentation, the locale module is a program-wide property according to the C standard definition. As a result, it is extremely expensive to change a locale in between.
Frequent locale changes may cause core dumps. That is why it is highly recommended to set it just once while initializing your application.
An extension module or library routine should never call the setlocale() function, since it will affect the entire program.
Apart from the format_string() function, the only way to perform numeric operations according to the locale is to use the special functions defined by this module:
- atof (convert a string to a floating point number),
- atoi (convert a string to integer),
- str (formats a floating point number using the same format as the built-in function str(float) but takes the decimal point into account).
Concluding our Guide to Python’s locale Module
In conclusion, the locale module is extremely useful for internationalizing and localizing Python applications. If you are looking for ways to streamline your i18n process, let Phrase do the heavy lifting. The most reliable translation management platform on the market comes with a 14-day free trial.
Phrase will equip you with everything you need to:
- Build production-ready integrations with your development workflow,
- Invite as many users as you wish to collaborate on your projects,
- Edit and convert localization files online with more context for higher translation quality.
Finally, check out the following articles if you want to know even more about internationalization and localization in Python:
The Ultimate Guide to Python Localization

Localizing Python applications is a process with many moving parts. But when done right, it can improve accessibility, increase user engagement, and expand market reach.
To help you get started, this tutorial will outline best practices for preparing Python apps for localization using JSON or YAML files, and discuss common modules available to help.
It will provide valuable insights for both developers looking to improve global appeal and businesses looking to expand into new markets.
How do I internationalize UI strings with Python?
Let’s address some key questions on how best to prepare your Python app for localization.
Why do we use translation files for our UI?
There are a couple of benefits to using translation files instead of hard-coding translation texts in your application:
- It is easier to edit and translate as most translators are not familiar with code
- You can easily identify the wrong translation texts without searching through your code base
- There is no need to rebuild your applications when there is a change to a translation (depending on programming languages and frameworks used)
At its core, translation files can be represented in different formats. The following section covers how to internationalize your Python application using:
- Custom implementation with JSON / YAML as translation files
- babel and gettext to work with PO and MO translation files
Installation
Before that, let’s install the following Python packages:
- babel : utilities for internationalization and localization in Python
- pyyaml : support reading and writing of YAML files
We can run the following commands from the command line to install our packages.
How to load JSON translation files?
One of the simplest methods to store translation files is via JSON. For example, you can create a new file called en.json with the following items:
Then, simply load it using the built-in json package as follows:
How to load YAML translation files?
We can use YAML files instead of JSON. We will need the pyyaml package to support YAML.
Given en.yaml as the translation file for English with the following content:
Likewise, the German translation file should be called de.yaml :
Load it using pyyaml package as follows:
Translator class
Using what you have learned so far, let’s build a custom module with a Translator class with the following features:
- Load translation files during startup
- Set the currently active locale
- Set the plural rules
- Translate and format the translation text
In addition, the module should also include 2 additional functions to:
- Convert a string to a datetime object
- Format a datetime object to a string
Make sure that your file structure is as follows:
Create a new Python file called i18n.py with the following code:
The glob module is used to load the translation files dynamically depending on the file_format value. It accepts either json or yaml :
The core feature is the translate function which returns the translation text based on the current active locale:
The module also contains 2 additional global functions for datetime formatting:
Adding interpolation to the Translator class
For string interpolation, you can use the built-in template string module. Add the following import statement:
Under the translate function, instead of returning the text variable directly, instantiate it with the Template class and call the safe_substitute function as follows:
Adding pluralization to the Translator class
You can import the babel.plural.PluralRule class for pluralization support:
Under the __init__ function, initialize a new plural_rule variable as follows:
Note » The module uses as the plural rule, which represents simple pluralization. The key should be one of the following:
- 0
- 1
- 2
- a few
- many
- other
Resource » The pluralization syntax is based on the CDLR rules.
Next, implement the setter and getter function for the plural rule in the Translator class:
Modify the code under the translate function to include a check for pluralization:
The complete code for the Translator class is as follows:
Using the Translator module in your application
Now, you can use the Translator class as a module in your application. Have a look at the following code snippet as a reference for the basic usage of the custom Translator module:
You can easily extend the functionality of the i18n module to support more features based on your requirements.
How do I internationalize my Python UI with gettext?
Alternatively, you can utilize the gettext module to internationalize Python applications. gettext uses PO (also known as POT) and MO message catalog files.
Note » PO files represent the human-editable translation files, while MO files are machine-readable for consumption by gettext .
Fortunately, the babel package complements nicely with the gettext module. babel provides the following utility functions for working with Message Catalogs:
- extract : extract messages from source files to generate a POT file
- init : create new message catalogs from a POT file
- update : update existing message catalogs in a POT file
- compile : compile POT files to MO files
Basic translation messages
The first phase is to mark strings as translatable in the source files. Simply enclose translatable strings with the _() function:
Note » _() is a short-hand alias of gettext.gettext() function. You can pass in the key for translation or the actual translation string as long as it is unique across the application. It will return the translated string based on the current locale.
For example, given that the code above resides in a Python file called main_babel.py , the command to extract messages from source files is as follows:
The output file, data/messages.pot , should contain the following content:
It represents the base translation file. msgid is the unique identifier for each message to be translated, while msgstr represents the translation text. You can leave msgstr empty for now as the actual translation text should be in the PO files.
The babel module will generate the relevant files for each locale automatically for you during the initialization phase. Let’s test it by running the following command for the en locale.
Note » -l sets the locale for the generated PO files.
Run another command again for de locale.
The content inside each messages.po file should be the same as the base POT file. The next step is to fill in the corresponding translation text inside the PO files:
Finally, run the following command to compile PO files into MO files:
The data folder should be as follows:
Once you are done with it, you can utilize the gettext.translation function to load the translation files.
For example, you can call the install function to set it as the currently active locale and get the translation text as follows:
Note » The install function will import the _() alias internally. Hence, there is no need to import _ manually.
Adding string interpolation via gettext
For string interpolation, you can use a variable name and mark it with curly brackets. For example, given the following translation text:
Note » Using curly brackets in the translation text allows string interpolation with the format function.
You can easily interpolate in the translation text as follows:
Adding pluralization support via ngettext
For pluralization support, use the ngettext function instead. It accepts 3 input arguments:
- singular : id for singular form
- plural : id for plural form
- n : plural determiner
Just like the gettext function, ngettext will return the translated string. You can easily interpolate in the output string with a function like format :
Upon extraction, you should see a different syntax in the base translation file (POT):
The number of msgstr is based on the number of plural forms specified for the locale. Different locales have different amounts of plural forms: While English has 2 plural forms, Arabic has 6.
A comment at the top of the file shows how a locale’s plural form for a message is resolved. For example:
Resource » The pluralization syntax is based on the CDLR rules.
Have a look at the following examples:
You can get the pluralized text as follows:
Using gettext in your application
Instead of loading each locale one by one, you can load the translation files dynamically and store them in a dict object as follows:
Now, simply set the desired locale and call either the _ or ngettext functions to get the desired translation texts:
Simply run the file as usual and you should get the same output as what we did previously using JSON or YAML.
Go deeper » Check out our guide to translating Python applications with the GNU gettext module to learn more about the gettext module.
How can a Python app support right-to-left languages?
Python does not come with an out-of-the-box implementation for displaying text meant for right-to-left languages, but you can utilize the python-bidi module for such use cases. python-bidi is a Python implementation of a bi-directional (BiDi) layout. It provides a convenient function to display right-to-left languages. Run the following command to install it:
It comes with the get_display function to display a string bi-directionally:
You should get the following output when you print the result:
How do I format localized dates and times in Python?
Python has its own built-in datetime module for manipulating dates and times. It supports arithmetic operations on objects, making it extremely useful for localization and internationalization.
How do I work with date and time duration?
A timedelta object represents the difference between 2 dates or times. You can think of it as a duration. It accepts the following input arguments:
You can create a new timedelta as follows:
Go deeper » Check out the Timedelta objects documentation to learn more about the Timedelta class.
How can I use datetimes?
A time object represents a local time of the day regardless of the date, while a date represents a date in a calendar. Often the ideal choice is to use the datetime object. It contains all the relevant information related to time and date. The datetime object can be categorized as naive or aware , depending on whether it contains information related to timezone.
Go deeper » Check out the Aware and Naive Objects documentation to learn more about them.
A datetime object supports the following methods for datetime conversion:
- strftime : convert a datetime object to a string according to a given format
- strptime : parse a string into a datetime object given a corresponding format
The strftime function accepts a string, which indicates the corresponding date and time format. This comes in handy when localizing the content of an application.
Go deeper » Check out the strftime and strptime documentation to learn more about them.
Have a look at the following code snippet which displays different string output depending on the input format string.
The format depends on the existing locale of the application. You can use the built-in locale module to change it.
Go deeper » Check out our beginner’s guide to Python’s locale module to learn more about the locale module.
Let’s test it again using de_DE (German in Germany) as the current locale instead:
On the other hand, the strptime function takes in 2 input arguments:
- date_string : a string representation of a datetime based on 1989 C standard.
- format : the format to parse the input date_string
Note » The strptime function cares about the current locale when parsing the input.
How do I format localized dates with Babel?
Alternatively, you can utilize the babel.dates module to format date and time.
A note on Babel
The babel module is a collection of utilities for l10n and i18n in Python. It is actively maintained and offers the following features:
- Datetime formatting
- Number formatting
- Currency formatting
- Generating message catalogs (translation files)
Go deeper » Check out Babel’s i18n advantages for multilingual apps to learn more about the babel module.
OK, back to date formatting. babel.dates comes with the following functions:
- format_time
- format_date
- format_datetime
Have a look at the following code snippet for the usage of Babel’s formatting functions:
The format argument is optional and can be one of the following choices:
- Short
- Medium (the default value)
- Long
- Full
Note » The final output is based on the input locale argument.
Go deeper » Check out the babel.dates fields documentation to learn more about custom patterns.
How do I use babel to work with time zones?
You can utilize the get_timezone function to create a new timezone object based on timezone names such as US/Eastern or Europe/Berlin . Then, pass the object as input for tzinfo argument:
How do I format localized numbers in Python?
Number formatting can be tricky when it comes to internationalization. For example, the text 12,345 conveys different meanings for English US ( en_US ) and German ( de_DE ). This is mainly because different languages use different symbols for decimal points and thousand separators.
Go deeper » Our concise guide to number localization covers grouping, separators, numeral systems, and more.
How do I use the built-in locale module to format numbers?
For conversion from string to integer or floating point, the locale module is a good option. It comes with the following built-in function:
- atoi : convert a string to an integer using the current locale numeric conventions
- atof : convert a string to a floating point using the current locale numeric conventions
Given 12,345 as the input string, the results of atof for both languages are as follows:
On the other hand, you can utilize the format_string function to convert a number into a localized string. It accepts the following input argument:
- format : a string representing the format specification
- val : a number
- grouping : whether to take grouping into account. Grouping refers to a sequence of numbers specifying which relative positions the thousand separator is expected. It is False by default.
Have a look at the following code snippet:
How do I use babel to format localized numbers?
Alternatively, you can utilize the following locale-specific formatting functions provided by the babel.numbers module:
- format_decimal : format a given number based on the input locale
- format_percent : format a given number to percentage based on the input locale
- format_scientific : format a given number to scientific notation based on the input locale. It uses E as the notation for power of 10
The following code snippet illustrates the output for format_decimal when using different locales:
Note » Unlike the locale.format_string function, the babel.numbers.format_decimal function allows parsing of custom patterns.
Go deeper » Check out the Custom Pattern Syntax documentation to learn more about custom patterns.
How do I format localized currency in Python?
Currency formatting takes into account the currency symbol and locale. For example, the symbols € and EUR represent euros and can be used interchangeably.
How do I use the built-in locale module to format currency?
The built-in locale module comes with the currency function to format currency. There is an optional international argument to display the currency using the international name instead of the currency symbol.
How do I use Babel to format localized currency?
The babel.numbers module comes with the format_currency function that considers both the locale and currency. It means that you can format a number using de_DE locale for USD .
Have a look at the following code snippet to understand more:
Note » Unlike the locale.format_currency function, the babel.numbers.format_currency function allows you to specify the currency explicitly. Instead of having USD bound to en_US locale, you can display the desired currency via the currency argument.
Wrapping up
We are done! By now, you should have all the knowledge required to localize and internationalize Python applications. If you are building web applications in Python and looking for built-in localization methods, consider checking out the following articles:
If you want to further streamline your localization process, consider signing up for Phrase, the most connective and customiziable suite of translation automation technology available.
Phrase comes with a 14-day free trial and can provide you with everything you need to:
как заставить питон писать по русски .
1. Какая трассировочная информация (какая именно ошибка) ? Думаю проблема с кодировкой.. .
Видимо python версии 2.7 либо ниже.. .
Если я прав, то есть еще raw_input()
Код где конкретно не работает, при запуске модуля или в интерактивном режиме?
В начале модуля указывали это?
# -*- coding: utf-8 -*-
Вот Вам пару строк для работы с кодировками:
import sys
print sys.getdefaultencoding() # в python 3.х print() — функция
# Выведет кодировку, используемую по-умолчанию.
# дело в том, что в питоне 3.х — используется utf8, а в 2.х — ansii
# основным изменением в python 3.2 является отсутствие разделение на строки
# юникода и строки байтов. Вместо этого был введен тип bytes.
import sys
reload(sys)
sys.setdefaultencoding(‘utf-8’)
# изменит кодировку по-умолчанию
Но в этом нет необходимости, обычно достаточно простого # -*- coding: utf-8 -*- в начале модуля, либо можно указать кодировку в настройках текстового редактора.