内容表

  • locale — 国际化服务
    • 背景、细节、提示、技巧和告诫
    • 用于嵌入 Python 的扩展写入器和程序
    • 访问消息分类

上一话题

就业培训     下载中心     Wiki     联络
登录   注册

Log
  1. 首页
  2. Python 3.12.4
  3. 索引
  4. 模块
  5. 下一
  6. 上一
  7. Python 标准库
  8. 国际化
  9. locale — 国际化服务

locale — 国际化服务 ¶

源代码: Lib/locale.py


The locale 模块打开对 POSIX 区域设置数据库和功能的访问。POSIX 区域设置机制允许程序员处理某些应用程序文化问题,不要求程序员知道每个执行软件国家的所有细节。

The locale 模块的实现是基于 _locale 模块,又使用了 ANSI C 区域设置实现,若可用。

The locale 模块定义了下列异常和函数:

exception 区域设置。 Error ¶

引发异常当区域设置被传递给 setlocale() 无法识别。

区域设置。 setlocale ( category , locale = None ) ¶

若 locale 有给定且不是 None , setlocale() 把区域设置修改为 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 被引发。若成功,返回新的区域设置。

若 locale 被省略或 None ,当前设置为 category 被返回。

setlocale() 在大多数系统中是非线程安全的。应用程序开始通常以调用

import locale
locale.setlocale(locale.LC_ALL, '')
													

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.

区域设置。 localeconv ( ) ¶

Returns the database of the local conventions as a dictionary. This dictionary has the following strings as keys:

类别

键

含义

LC_NUMERIC

'decimal_point'

小数点字符。

'grouping'

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.

'thousands_sep'

用于组间的字符。

LC_MONETARY

'int_curr_symbol'

国际货币符号。

'currency_symbol'

本地货币符号。

'p_cs_precedes/n_cs_precedes'

Whether the currency symbol precedes the value (for positive resp. negative values).

'p_sep_by_space/n_sep_by_space'

Whether the currency symbol is separated from the value by a space (for positive resp. negative values).

'mon_decimal_point'

Decimal point used for monetary values.

'frac_digits'

Number of fractional digits used in local formatting of monetary values.

'int_frac_digits'

Number of fractional digits used in international formatting of monetary values.

'mon_thousands_sep'

Group separator used for monetary values.

'mon_grouping'

相当于 'grouping' ,用于货币值。

'positive_sign'

Symbol used to annotate a positive monetary value.

'negative_sign'

Symbol used to annotate a negative monetary value.

'p_sign_posn/n_sign_posn'

The position of the sign (for positive resp. negative values), see below.

所有数值可以被设为 CHAR_MAX 以指示此区域设置中不存在指定值。

可能的值对于 'p_sign_posn' and 'n_sign_posn' 给定如下。

值

解释

0

Currency and value are surrounded by parentheses.

1

The sign should precede the value and currency symbol.

2

The sign should follow the value and currency symbol.

3

The sign should immediately precede the value.

4

The sign should immediately follow the value.

CHAR_MAX

Nothing is specified in this locale.

The function temporarily sets the LC_CTYPE 区域设置到 LC_NUMERIC 区域设置或 LC_MONETARY locale if locales are different and numeric or monetary strings are non-ASCII. This temporary change affects other threads.

3.7 版改变: The function now temporarily sets the LC_CTYPE 区域设置到 LC_NUMERIC 区域设置在某些情况下。

区域设置。 nl_langinfo ( option ) ¶

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.

区域设置。 CODESET ¶

Get a string with the name of the character encoding used in the selected locale.

区域设置。 D_T_FMT ¶

Get a string that can be used as a format string for time.strftime() to represent date and time in a locale-specific way.

区域设置。 D_FMT ¶

Get a string that can be used as a format string for time.strftime() to represent a date in a locale-specific way.

区域设置。 T_FMT ¶

Get a string that can be used as a format string for time.strftime() to represent a time in a locale-specific way.

区域设置。 T_FMT_AMPM ¶

获取格式字符串为 time.strftime() 以 am/pm 格式表示时间。

区域设置。 DAY_1 ¶
区域设置。 DAY_2 ¶
区域设置。 DAY_3 ¶
区域设置。 DAY_4 ¶
区域设置。 DAY_5 ¶
区域设置。 DAY_6 ¶
区域设置。 DAY_7 ¶

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.

区域设置。 ABDAY_1 ¶
区域设置。 ABDAY_2 ¶
区域设置。 ABDAY_3 ¶
区域设置。 ABDAY_4 ¶
区域设置。 ABDAY_5 ¶
区域设置。 ABDAY_6 ¶
区域设置。 ABDAY_7 ¶

Get the abbreviated name of the n-th day of the week.

区域设置。 MON_1 ¶
区域设置。 MON_2 ¶
区域设置。 MON_3 ¶
区域设置。 MON_4 ¶
区域设置。 MON_5 ¶
区域设置。 MON_6 ¶
区域设置。 MON_7 ¶
区域设置。 MON_8 ¶
区域设置。 MON_9 ¶
区域设置。 MON_10 ¶
区域设置。 MON_11 ¶
区域设置。 MON_12 ¶

获取第 n 个月的名称。

区域设置。 ABMON_1 ¶
区域设置。 ABMON_2 ¶
区域设置。 ABMON_3 ¶
区域设置。 ABMON_4 ¶
区域设置。 ABMON_5 ¶
区域设置。 ABMON_6 ¶
区域设置。 ABMON_7 ¶
区域设置。 ABMON_8 ¶
区域设置。 ABMON_9 ¶
区域设置。 ABMON_10 ¶
区域设置。 ABMON_11 ¶
区域设置。 ABMON_12 ¶

Get the abbreviated name of the n-th month.

区域设置。 RADIXCHAR ¶

Get the radix character (decimal dot, decimal comma, etc.).

区域设置。 THOUSEP ¶

Get the separator character for thousands (groups of three digits).

区域设置。 YESEXPR ¶

Get a regular expression that can be used with the regex function to recognize a positive response to a yes/no question.

区域设置。 NOEXPR ¶

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 .

区域设置。 CRNCYSTR ¶

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.

区域设置。 ERA ¶

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.

区域设置。 ERA_D_T_FMT ¶

获取格式字符串为 time.strftime() to represent date and time in a locale-specific era-based way.

区域设置。 ERA_D_FMT ¶

获取格式字符串为 time.strftime() to represent a date in a locale-specific era-based way.

区域设置。 ERA_T_FMT ¶

获取格式字符串为 time.strftime() to represent a time in a locale-specific era-based way.

区域设置。 ALT_DIGITS ¶

Get a representation of up to 100 values used to represent the values 0 to 99.

区域设置。 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 可以是 None if their values cannot be determined.

Deprecated since version 3.11, will be removed in version 3.15.

区域设置。 getlocale ( category = LC_CTYPE ) ¶

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 。默认为 LC_CTYPE .

Except for the code 'C' , the language code corresponds to RFC 1766 . language code and encoding 可以是 None if their values cannot be determined.

区域设置。 getpreferredencoding ( do_setlocale = True ) ¶

返回 区域设置编码 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.

在某些系统,有必要援引 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 .

在 Android 或者若 Python UTF-8 模式 被启用,始终返回 'utf-8' , 区域设置编码 和 do_setlocale 自变量被忽略。

The Python 预初始化 配置 LC_CTYPE 区域设置。另请参阅 文件系统编码和错误处理程序 .

3.7 版改变: 函数现在始终返回 "utf-8" 在 Android 或者若 Python UTF-8 模式 被启用。

区域设置。 getencoding ( ) ¶

获取当前 区域设置编码 :

  • 在 Android 和 VxWorks,返回 "utf-8" .

  • 在 Unix,返回编码为当前 LC_CTYPE 区域设置。返回 "utf-8" if nl_langinfo(CODESET) 返回空字符串:例如,若不支持当前 LC_CTYPE 区域设置。

  • 在 Windows,返回 ANSI 代码页。

The Python 预初始化 配置 LC_CTYPE 区域设置。另请参阅 文件系统编码和错误处理程序 .

此函数类似于 getpreferredencoding(False) 除了此函数忽略 Python UTF-8 模式 .

Added in version 3.11.

区域设置。 normalize ( localename ) ¶

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() .

区域设置。 resetlocale ( category = LC_ALL ) ¶

设置区域设置为 category 到默认设置。

默认设置的确定是通过调用 getdefaultlocale() . category 默认为 LC_ALL .

从 3.11 版起弃用,将在 3.13 版中移除。

区域设置。 strcoll ( string1 , string2 ) ¶

比较 2 字符串根据当前 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.

区域设置。 strxfrm ( string ) ¶

Transforms a string to one that can be used in locale-aware comparisons. For example, strxfrm(s1) < strxfrm(s2) 相当于 strcoll(s1, s2) < 0 . This function can be used when the same string is compared repeatedly, e.g. when collating a sequence of strings.

区域设置。 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.

若 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.

3.7 版改变: The monetary keyword parameter was added.

区域设置。 currency ( val , symbol = True , grouping = False , international = False ) ¶

Formats a number val according to the current LC_MONETARY 设置。

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() 首先。

区域设置。 str ( float ) ¶

Formats a floating point number using the same format as the built-in function str(float) , but takes the decimal point into account.

区域设置。 delocalize ( string ) ¶

Converts a string into a normalized number string, following the LC_NUMERIC 设置。

Added in version 3.5.

区域设置。 localize ( string , grouping = False , monetary = False ) ¶

Converts a normalized number string into a formatted string following the LC_NUMERIC 设置。

Added in version 3.10.

区域设置。 atof ( string , func = float ) ¶

Converts a string to a number, following the LC_NUMERIC settings, by calling func on the result of calling delocalize() on string .

区域设置。 atoi ( string ) ¶

Converts a string to an integer, following the LC_NUMERIC 约定。

区域设置。 LC_CTYPE ¶

Locale category for the character type functions. Most importantly, this category defines the text encoding, i.e. how bytes are interpreted as Unicode codepoints. See PEP 538 and PEP 540 for how this variable might be automatically coerced to C.UTF-8 to avoid issues created by invalid settings in containers or incompatible settings passed over remote SSH connections.

Python doesn’t internally use locale-dependent character transformation functions from ctype.h . Instead, an internal pyctype.h provides locale-independent equivalents like Py_TOLOWER .

区域设置。 LC_COLLATE ¶

Locale category for sorting strings. The functions strcoll() and strxfrm() 的 locale module are affected.

区域设置。 LC_TIME ¶

Locale category for the formatting of time. The function time.strftime() follows these conventions.

区域设置。 LC_MONETARY ¶

Locale category for formatting of monetary values. The available options are available from the localeconv() 函数。

区域设置。 LC_MESSAGES ¶

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.

区域设置。 LC_NUMERIC ¶

Locale category for formatting numbers. The functions format_string() , atoi() , atof() and str() 的 locale module are affected by that category. All other numeric formatting operations are not affected.

区域设置。 LC_ALL ¶

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.

区域设置。 CHAR_MAX ¶

This is a symbolic constant used for different values returned by localeconv() .

范例:

>>> import locale
>>> loc = locale.getlocale()  # get current locale
# use German locale; name might vary with platform
>>> locale.setlocale(locale.LC_ALL, 'de_DE')
>>> locale.strcoll('f\xe4n', 'foo')  # compare a string containing an umlaut
>>> locale.setlocale(locale.LC_ALL, '')   # use user's preferred locale
>>> locale.setlocale(locale.LC_ALL, 'C')  # use default (C) locale
>>> locale.setlocale(locale.LC_ALL, loc)  # restore saved locale
											

背景、细节、提示、技巧和告诫 ¶

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_string() , 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.

用于嵌入 Python 的扩展写入器和程序 ¶

扩展模块从不应调用 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.

访问消息分类 ¶

区域设置。 gettext ( msg ) ¶
区域设置。 dgettext ( domain , msg ) ¶
区域设置。 dcgettext ( domain , msg , category ) ¶
区域设置。 textdomain ( domain ) ¶
区域设置。 bindtextdomain ( domain , dir ) ¶
区域设置。 bind_textdomain_codeset ( domain , codeset ) ¶

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() ,和 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 C functions 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.

内容表

  • locale — 国际化服务
    • 背景、细节、提示、技巧和告诫
    • 用于嵌入 Python 的扩展写入器和程序
    • 访问消息分类

上一话题

gettext — 多语言国际化服务

下一话题

程序框架

本页

  • 报告 Bug
  • 展示源

快速搜索

键入搜索术语或模块、类、函数名称。

  1. 首页
  2. Python 3.12.4
  3. 索引
  4. 模块
  5. 下一
  6. 上一
  7. Python 标准库
  8. 国际化
  9. locale — 国际化服务

版权所有  © 2014-2026 乐数软件    

工业和信息化部: 粤ICP备14079481号-1