string --- 常見的字串操作

原始碼:Lib/string/__init__.py


字串常數

此模組中定義的常數為:

string.ascii_letters

下文描述的 ascii_lowercaseascii_uppercase 常數的串接,該值不依賴於區域設定。

string.ascii_lowercase

小寫字母 'abcdefghijklmnopqrstuvwxyz'。該值與地區設定無關且不會改變。

string.ascii_uppercase

大寫字母 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'。此值與地區設定無關且不會改變。

string.digits

字串 '0123456789'

string.hexdigits

字串 '0123456789abcdefABCDEF'

string.octdigits

字串 '01234567'

string.punctuation

C 語言中被視為標點符號的 ASCII 字元的字串:!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

string.printable

ASCII 字元的字串被 Python 是為可被列印輸出的。這是 digitsascii_letterspunctuationwhitespace 的組合。

備註

By design, string.printable.isprintable() returns False. In particular, string.printable is not printable in the POSIX sense (see LC_CTYPE).

string.whitespace

包含所有 ASCII 字元的字串都視為空白字元 (whitespace)。 包含空格 (space)、製表符號 (tab)、換行符號 (linefeed)、return、換頁符號 (formfeed) 和垂直製表符號 (vertical tab) 這些字元。

自訂字串格式

透過 PEP 3101 中描述的 format() 方法,內建字串類別提供了進行複雜變數替換和數值格式化的能力。string 模組中的 Formatter 類別模組可讓你使用與內建 format() 方法相同的實作來建立和自訂你自己的字串格式化行為。

class string.Formatter

Formatter 類別有以下的公開方法:

format(format_string, /, *args, **kwargs)

主要的 API 方法。它接收一個格式字串及一組任意的位置引數與關鍵字引數,是呼叫 vformat() 的包裝器 (wrapper)。

在 3.7 版的變更: 現在格式字串引數是僅限位置參數

vformat(format_string, args, kwargs)

This function does the actual work of formatting. It is exposed as a separate function for cases where you want to pass in a predefined dictionary of arguments, rather than unpacking and repacking the dictionary as individual arguments using the *args and **kwargs syntax. vformat() does the work of breaking up the format string into character data and replacement fields. It calls the various methods described below.

In addition, the Formatter defines a number of methods that are intended to be replaced by subclasses:

parse(format_string)

將 format_string 放入迴圈,並回傳一個可疊代物件,其元素為 (literal_text, field_name, format_spec, conversion)。這會被 vformat() 用於將字串裁切為字面文本或替換欄位。

The values in the tuple conceptually represent a span of literal text followed by a single replacement field. If there is no literal text (which can happen if two replacement fields occur consecutively), then literal_text will be a zero-length string. If there is no replacement field, then the values of field_name, format_spec and conversion will be None. The value of field_name is unmodified and auto-numbering of non-numbered positional fields is done by vformat().

get_field(field_name, args, kwargs)

Given field_name, convert it to an object to be formatted. Auto-numbering of field_name returned from parse() is done by vformat() before calling this method. Returns a tuple (obj, used_key). The default version takes strings of the form defined in PEP 3101, such as "0[name]" or "label.title". args and kwargs are as passed in to vformat(). The return value used_key has the same meaning as the key parameter to get_value().

get_value(key, args, kwargs)

Retrieve a given field value. The key argument will be either an integer or a string. If it is an integer, it represents the index of the positional argument in args; if it is a string, then it represents a named argument in kwargs.

The args parameter is set to the list of positional arguments to vformat(), and the kwargs parameter is set to the dictionary of keyword arguments.

For compound field names, these functions are only called for the first component of the field name; subsequent components are handled through normal attribute and indexing operations.

So for example, the field expression '0.name' would cause get_value() to be called with a key argument of 0. The name attribute will be looked up after get_value() returns by calling the built-in getattr() function.

If the index or keyword refers to an item that does not exist, then an IndexError or KeyError should be raised.

check_unused_args(used_args, args, kwargs)

Implement checking for unused arguments if desired. The arguments to this function is the set of all argument keys that were actually referred to in the format string (integers for positional arguments, and strings for named arguments), and a reference to the args and kwargs that was passed to vformat. The set of unused args can be calculated from these parameters. check_unused_args() is assumed to raise an exception if the check fails.

format_field(value, format_spec)

format_field() simply calls the global format() built-in. The method is provided so that subclasses can override it.

convert_field(value, conversion)

Converts the value (returned by get_field()) given a conversion type (as in the tuple returned by the parse() method). The default version understands 's' (str), 'r' (repr) and 'a' (ascii) conversion types.

格式化文字語法

The str.format() method and the Formatter class share the same syntax for format strings (although in the case of Formatter, subclasses can define their own format string syntax). The syntax is related to that of formatted string literals and template string literals, but it is less sophisticated and, in particular, does not support arbitrary expressions in interpolations.

Format strings contain "replacement fields" surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

The grammar for a replacement field is as follows:

replacement_field: "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name:        arg_name ("." attribute_name | "[" element_index "]")*
arg_name:          [identifier | digit+]
attribute_name:    identifier
element_index:     digit+ | index_string
index_string:      <any source character except "]"> +
conversion:        "r" | "s" | "a"
format_spec:       format-spec:format_spec

In less formal terms, the replacement field can start with a field_name that specifies the object whose value is to be formatted and inserted into the output instead of the replacement field. The field_name is optionally followed by a conversion field, which is preceded by an exclamation point '!', and a format_spec, which is preceded by a colon ':'. These specify a non-default format for the replacement value.

另請參閱 格式規格 (Format Specification) 迷你語言 部份。

The field_name itself begins with an arg_name that is either a number or a keyword. If it's a number, it refers to a positional argument, and if it's a keyword, it refers to a named keyword argument. An arg_name is treated as a number if a call to str.isdecimal() on the string would return true. If the numerical arg_names in a format string are 0, 1, 2, ... in sequence, they can all be omitted (not just some) and the numbers 0, 1, 2, ... will be automatically inserted in that order. Because arg_name is not quote-delimited, it is not possible to specify arbitrary dictionary keys (e.g., the strings '10' or ':-]') within a format string. The arg_name can be followed by any number of index or attribute expressions. An expression of the form '.name' selects the named attribute using getattr(), while an expression of the form '[index]' does an index lookup using __getitem__().

在 3.1 版的變更: The positional argument specifiers can be omitted for str.format(), so '{} {}'.format(a, b) is equivalent to '{0} {1}'.format(a, b).

在 3.4 版的變更: The positional argument specifiers can be omitted for Formatter.

Some simple format string examples:

"First, thou shalt count to {0}"  # References first positional argument
"Bring me a {}"                   # Implicitly references the first positional argument
"From {} to {}"                   # Same as "From {0} to {1}"
"My quest is {name}"              # References keyword argument 'name'
"Weight in tons {0.weight}"       # 'weight' attribute of first positional arg
"Units destroyed: {players[0]}"   # First element of keyword argument 'players'.

The conversion field causes a type coercion before formatting. Normally, the job of formatting a value is done by the __format__() method of the value itself. However, in some cases it is desirable to force a type to be formatted as a string, overriding its own definition of formatting. By converting the value to a string before calling __format__(), the normal formatting logic is bypassed.

目前支援三種轉換旗標:'!s' 會對該值呼叫 str()'!r' 會對該值呼叫 repr(),而 '!a' 則會對該值呼叫 ascii()

一些範例:

"Harold's a clever {0!s}"        # Calls str() on the argument first
"Bring out the holy {name!r}"    # Calls repr() on the argument first
"More {!a}"                      # Calls ascii() on the argument first

format_spec 欄位描述了值的呈現規格,例如欄位寬度、對齊、填充 (padding)、小數精度等細節資訊。每種值類型都可以定義自己的「格式化迷你語言 (formatting mini-language)」或對 format_spec 的解釋。

大多數內建型別都支援常見的格式化迷你語言,下一節將會詳細說明。

format_spec 欄位還可以在其內部包含巢狀的替換欄位。這些巢狀的替換欄位可能包含欄位名稱、轉換旗標、格式規格描述,但是不允許再更深層的巢狀結構。format_spec 內部的替換欄位會在 format_spec 字串被直譯前被替換。這讓數值的格式能夠被動態地指定。

範例請見 格式範例

格式規格 (Format Specification) 迷你語言

「格式規格」在格式字串 (format string) 中包含的替換欄位中使用,以定義各個值如何被呈現(請參考 格式化文字語法f-string(f 字串)t-string(t 字串))。它們也能夠直接傳遞給內建的 format() 函式。每個可格式化型別 (formattable type) 可以定義格式規格如何被直譯。

大部分內建型別為了格式規格實作了下列選項,不過有些選項只被數值型別支援。

一般來說,輸入空格式規格會產生和對值呼叫 str() 函式相同的結果,非空的格式規格才會修改結果。

標準格式說明符號 (standard format specifier) 的一般型式如下:

format_spec:             [options][width_and_precision][type]
options:                 [[fill]align][sign]["z"]["#"]["0"]
fill:                    <any character>
align:                   "<" | ">" | "=" | "^"
sign:                    "+" | "-" | " "
width_and_precision:     [width_with_grouping][precision_with_grouping]
width_with_grouping:     [width][grouping]
precision_with_grouping: "." [precision][grouping] | "." grouping
width:                   digit+
precision:               digit+
grouping:                "," | "_"
type:                    "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g"
                         | "G" | "n" | "o" | "s" | "x" | "X" | "%"

如果給定了一個有效的 align 值,則可以在它之前加一個 fill 字元,且該字元可為任意字元,若不加的話預設為空格。使用格式字串str.format() 時是無法在其中使用大括號("{" 或 "}")作為 fill 字元的,但仍可透過巢狀替換欄位的方式插入大括號。此限制不影響 format() 函式。

The meaning of the various alignment options is as follows:

選項

含義

'<'

強制欄位在可用空間內靠左對齊(這是大多數物件的預設值)。

'>'

強制欄位在可用空間內靠右對齊(這是數字的預設值)。

'='

Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form '+000000120'. This alignment option is only valid for numeric types, excluding complex. It becomes the default for numbers when '0' immediately precedes the field width.

'^'

強制欄位在可用空間內置中。

請注意,除非有定義了最小欄位寬度,否則欄位寬度將始終與填充它的資料大小相同,故在該情況下的對齊選項是沒有意義的。

sign 選項只適用於數字型別,並可為以下之一:

選項

含義

'+'

表示正數與負數均需使用符號。

'-'

表示正數應使用前導空格,負數應使用減號。

空格

表示正數應使用前導空格,負數應使用減號。

The 'z' option coerces negative zero floating-point values to positive zero after rounding to the format precision. This option is only valid for floating-point presentation types.

在 3.11 版的變更: 新增 'z' 選項(請見 PEP 682)。

The '#' option causes the "alternate form" to be used for the conversion. The alternate form is defined differently for different types. This option is only valid for integer, float and complex types. For integers, when binary, octal, or hexadecimal output is used, this option adds the respective prefix '0b', '0o', '0x', or '0X' to the output value. For float and complex the alternate form causes the result of the conversion to always contain a decimal-point character, even if no digits follow it. Normally, a decimal-point character appears in the result of these conversions only if a digit follows it. In addition, for 'g' and 'G' conversions, trailing zeros are not removed from the result.

width 是一個十進位整數,定義了最小總欄位寬度,包括任何前綴、分隔符號和其他格式字元。如果未指定,則欄位寬度將由內容決定。

當未給予明確的對齊指示,在 width 欄位前面填入零 ('0') 字元將會為 complex 以外的數值型別啟用有符號察覺的零填充 (sign-aware zero-padding)。這相當於使用 '0'fill 字元且對齊類型為 '='

在 3.10 版的變更: width 欄位前面加上 '0' 不再影響字串的預設對齊方式。

precision 是一個十進位整數,指定表示類型 'f''F' 的小數點後應顯示多少位,或表示類型 'g''G' 的小數點前後應顯示多少位。對於字串表示類型,該欄位指定最大欄位大小 - 換言之,將使用欄位中的多少字元。整數表示類型不允許使用 precision

The grouping option after width and precision fields specifies a digit group separator for the integral and fractional parts of a number respectively. It can be one of the following:

選項

含義

','

Inserts a comma every 3 digits for integer presentation type 'd' and floating-point presentation types, excluding 'n'. For other presentation types, this option is not supported.

'_'

在整數表示型別 'd' 和浮點數表示型別中,每 3 位數插入一個底線,這不包括 'n'。對於整數表示型別 'b''o''x''X',每 4 位數字會插入底線。對於其他表示型別來說此選項並不支援。

For a locale aware separator, use the 'n' presentation type instead.

在 3.1 版的變更: 新增 ',' 選項(請見 PEP 378)。

在 3.6 版的變更: 新增 '_' 選項(請見 PEP 515)。

在 3.14 版的變更: Support the grouping option for the fractional part.

最終,型別決定了資料將會如何呈現

可用的字串表示型別有:

型別

含義

's'

String format. This is the default type for strings and may be omitted.

None

's' 相同。

The available integer presentation types are:

型別

含義

'b'

Binary format. Outputs the number in base 2.

'c'

Character. Converts the integer to the corresponding unicode character before printing.

'd'

Decimal Integer. Outputs the number in base 10.

'o'

Octal format. Outputs the number in base 8.

'x'

十六進位格式。輸出以 16 為基數的數字,9 以上的數字使用小寫字母。

'X'

十六進位格式。輸出以 16 為基數的數字,9 以上的數字使用大寫字母。如果指定了 '#',則前綴 '0x' 也會被轉成大寫的 '0X'

'n'

Number. This is the same as 'd', except that it uses the current locale setting to insert the appropriate digit group separators.

None

'd' 相同。

In addition to the above presentation types, integers can be formatted with the floating-point presentation types listed below (except 'n' and None). When doing so, float() is used to convert the integer to a floating-point number before formatting.

The available presentation types for float and Decimal values are:

型別

含義

'e'

Scientific notation. For a given precision p, formats the number in scientific notation with the letter 'e' separating the coefficient from the exponent. The coefficient has one digit before and p digits after the decimal point, for a total of p + 1 significant digits. With no precision given, uses a precision of 6 digits after the decimal point for float, and shows all coefficient digits for Decimal. If p=0, the decimal point is omitted unless the # option is used.

For float, the exponent always contains at least two digits, and is zero if the value is zero.

'E'

Scientific notation. Same as 'e' except it uses an upper case 'E' as the separator character.

'f'

Fixed-point notation. For a given precision p, formats the number as a decimal number with exactly p digits following the decimal point. With no precision given, uses a precision of 6 digits after the decimal point for float, and uses a precision large enough to show all coefficient digits for Decimal. If p=0, the decimal point is omitted unless the # option is used.

'F'

Fixed-point notation. Same as 'f', but converts nan to NAN and inf to INF.

'g'

General format. For a given precision p >= 1, this rounds the number to p significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude. A precision of 0 is treated as equivalent to a precision of 1.

The precise rules are as follows: suppose that the result formatted with presentation type 'e' and precision p-1 would have exponent exp. Then, if m <= exp < p, where m is -4 for floats and -6 for Decimals, the number is formatted with presentation type 'f' and precision p-1-exp. Otherwise, the number is formatted with presentation type 'e' and precision p-1. In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it, unless the '#' option is used.