string --- 常見的字串操作

原始碼:Lib/string.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()returnsFalse. In particular,string.printable is notprintable in the POSIX sense (seeLC_CTYPE).

string.whitespace

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

自訂字串格式

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

classstring.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 aseparate function for cases where you want to pass in a predefineddictionary of arguments, rather than unpacking and repacking thedictionary as individual arguments using the*args and**kwargssyntax.vformat() does the work of breaking up the format stringinto character data and replacement fields. It calls the variousmethods described below.

In addition, theFormatter defines a number of methods that areintended 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 textfollowed by a single replacement field. If there is no literal text(which can happen if two replacement fields occur consecutively), thenliteral_text will be a zero-length string. If there is no replacementfield, then the values offield_name,format_spec andconversionwill beNone.

get_field(field_name,args,kwargs)

Givenfield_name as returned byparse() (see above), convert it toan object to be formatted. Returns a tuple (obj, used_key). The defaultversion takes strings of the form defined inPEP 3101, such as"0[name]" or "label.title".args andkwargs are as passed in tovformat(). The return valueused_key has the same meaning as thekey parameter toget_value().

get_value(key,args,kwargs)

Retrieve a given field value. Thekey argument will be either aninteger or a string. If it is an integer, it represents the index of thepositional argument inargs; if it is a string, then it represents anamed argument inkwargs.

Theargs parameter is set to the list of positional arguments tovformat(), and thekwargs parameter is set to the dictionary ofkeyword arguments.

For compound field names, these functions are only called for the firstcomponent of the field name; subsequent components are handled throughnormal attribute and indexing operations.

So for example, the field expression '0.name' would causeget_value() to be called with akey argument of 0. Thenameattribute will be looked up afterget_value() returns by calling thebuilt-ingetattr() function.

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

check_unused_args(used_args,args,kwargs)

Implement checking for unused arguments if desired. The arguments to thisfunction is the set of all argument keys that were actually referred to inthe format string (integers for positional arguments, and strings fornamed arguments), and a reference to theargs andkwargs that waspassed to vformat. The set of unused args can be calculated from theseparameters.check_unused_args() is assumed to raise an exception ifthe check fails.

format_field(value,format_spec)

format_field() simply calls the globalformat() built-in. Themethod is provided so that subclasses can override it.

convert_field(value,conversion)

Converts the value (returned byget_field()) given a conversion type(as in the tuple returned by theparse() method). The defaultversion understands 's' (str), 'r' (repr) and 'a' (ascii) conversiontypes.

格式化文字語法

Thestr.format() method and theFormatter class share the samesyntax for format strings (although in the case ofFormatter,subclasses can define their own format string syntax). The syntax isrelated to that offormatted string literals, but it isless sophisticated and, in particular, does not support arbitrary expressions.

Format strings contain "replacement fields" surrounded by curly braces{}.Anything that is not contained in braces is considered literal text, which iscopied unchanged to the output. If you need to include a brace character in theliteral 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    ::=identifierelement_index     ::=digit+ |index_stringindex_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 afield_name that specifiesthe object whose value is to be formatted and insertedinto the output instead of the replacement field.Thefield_name is optionally followed by aconversion field, which ispreceded by an exclamation point'!', and aformat_spec, which is precededby a colon':'. These specify a non-default format for the replacement value.

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

Thefield_name itself begins with anarg_name that is either a number or akeyword. If it's a number, it refers to a positional argument, and if it's a keyword,it refers to a named keyword argument. Anarg_name is treated as a number ifa call tostr.isdecimal() on the string would return true.If the numerical arg_names in a format stringare 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.Becausearg_name is not quote-delimited, it is not possible to specify arbitrarydictionary keys (e.g., the strings'10' or':-]') within a format string.Thearg_name can be followed by any number of index orattribute expressions. An expression of the form'.name' selects the namedattribute usinggetattr(), while an expression of the form'[index]'does an index lookup using__getitem__().

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

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

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

Theconversion field causes a type coercion before formatting. Normally, thejob of formatting a value is done by the__format__() method of the valueitself. However, in some cases it is desirable to force a type to be formattedas a string, overriding its own definition of formatting. By converting thevalue to a string before calling__format__(), the normal formatting logicis 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 字串))。它們也能夠直接傳遞給內建的format() 函式。每個可格式化型別 (formattable type) 可以定義格式規格如何被直譯。

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

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

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

format_spec ::= [options][width][grouping]["."precision][type]options     ::= [[fill]align][sign]["z"]["#"]["0"]fill        ::= <any character>align       ::= "<" | ">" | "=" | "^"sign        ::= "+" | "-" | " "width       ::=digit+grouping    ::= "," | "_"precision   ::=digit+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 fieldsin the form '+000000120'. This alignment option is onlyvalid for numeric types, excludingcomplex.It becomes the default for numbers when '0' immediatelyprecedes the field width.

'^'

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

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

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

選項

含義

'+'

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

'-'

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

空格

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

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

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

The'#' option causes the "alternate form" to be used for theconversion. The alternate form is defined differently for differenttypes. This option is only valid for integer, float and complextypes. For integers, when binary, octal, or hexadecimal outputis used, this option adds the respective prefix'0b','0o','0x', or'0X' to the output value. For float and complex thealternate form causes the result of the conversion to always contain adecimal-point character, even if no digits follow it. Normally, adecimal-point character appears in the result of these conversionsonly 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' 不再影響字串的預設對齊方式。

Thegrouping option after thewidth field specifiesa digit group separator for the integral part of a number.It can be one of the following:

選項

含義

','

Inserts a comma every 3 digits forinteger presentation type'd' andfloating-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)。

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

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

可用的字串表示型別有:

型別

含義

's'

String format. This is the default type for strings andmay 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 correspondingunicode 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 usesthe current locale setting to insert the appropriatedigit group separators.

None

'd' 相同。

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

The available presentation types forfloat andDecimal values are:

型別

含義

'e'

Scientific notation. For a given precisionp,formats the number in scientific notation with theletter 'e' separating the coefficient from the exponent.The coefficient has one digit before andp digitsafter the decimal point, for a total ofp+1significant digits. With no precision given, uses aprecision of6 digits after the decimal point forfloat, and shows all coefficient digitsforDecimal. Ifp=0, the decimalpoint is omitted unless the# option is used.

'E'

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

'f'

Fixed-point notation. For a given precisionp,formats the number as a decimal number with exactlyp digits following the decimal point. With noprecision given, uses a precision of6 digits afterthe decimal point forfloat, and uses aprecision large enough to show all coefficient digitsforDecimal. Ifp=0, the decimalpoint is omitted unless the# option is used.

'F'

Fixed-point notation. Same as'f', but convertsnan toNAN andinf toINF.

'g'

General format. For a given precisionp>=1,this rounds the number top significant digits andthen formats the result in either fixed-point formator in scientific notation, depending on its magnitude.A precision of0 is treated as equivalent to aprecision of1.

The precise rules are as follows: suppose that theresult formatted with presentation type'e' andprecisionp-1 would have exponentexp. Then,ifm<=exp<p, wherem is -4 for floats and -6forDecimals, the number isformatted with presentation type'f' and precisionp-1-exp. Otherwise, the number is formattedwith presentation type'e' and precisionp-1.In both cases insignificant trailing zeros are removedfrom the significand, and the decimal point is alsoremoved if there are no remaining digits following it,unless the'#' option is used.

With no precision given, uses a precision of6significant digits forfloat. ForDecimal, the coefficient of the resultis formed from the coefficient digits of the value;scientific notation is used for values smaller than1e-6 in absolute value and values where the placevalue of the least significant digit is larger than 1,and fixed-point notation is used otherwise.

Positive and negative infinity, positive and negativezero, and nans, are formatted asinf,-inf,0,-0 andnan respectively, regardless ofthe precision.

'G'

General format. Same as'g' except switches to'E' if the number gets too large. Therepresentations of infinity and NaN are uppercased, too.

'n'

Number. This is the same as'g', except that it usesthe current locale setting to insert the appropriatedigit group separatorsfor the integral part of a number.

'%'

Percentage. Multiplies the number by 100 and displaysin fixed ('f') format, followed by a percent sign.

None

Forfloat this is like the'g' type, exceptthat when fixed-point notation is used to format theresult, it always includes at least one digit past thedecimal point, and switches to the scientific notationwhenexp>=p-1. When the precision is notspecified, the latter will be as large as needed torepresent the given value faithfully.

ForDecimal, this is the same aseither'g' or'G' depending on the value ofcontext.capitals for the current decimal context.

The overall effect is to match the output ofstr()as altered by the other format modifiers.

The result should be correctly rounded to a given precisionp of digitsafter the decimal point. The rounding mode forfloat matches thatof theround() builtin. ForDecimal, the roundingmode of the currentcontext will be used.

The available presentation types forcomplex are the same as those forfloat ('%' is not allowed). Both the real and imaginary componentsof a complex number are formatted as floating-point numbers, according to thespecified presentation type. They are separated by the mandatory sign of theimaginary part, the latter being terminated by aj suffix. If the presentationtype is missing, the result will match the output ofstr() (complex numbers witha non-zero real part are also surrounded by parentheses), possibly altered byother format modifiers.

格式範例

本節包含str.format() 語法以及與舊式% 格式的比較。

此語法在大多情況下與舊式的% 格式類似,只是增加了{}: 來取代%。例如,'%03.2f' 可以改寫為'{:03.2f}'

新的語法還支援新的選項,將在以下的範例中說明。

按位置存取引數:

>>>'{0},{1},{2}'.format('a','b','c')'a, b, c'>>>'{},{},{}'.format('a','b','c')# 3.1+ only'a, b, c'>>>'{2},{1},{0}'.format('a','b','c')'c, b, a'>>>'{2},{1},{0}'.format(*'abc')# 解包引數序列'c, b, a'>>>'{0}{1}{0}'.format('abra','cad')# 引數索引可以重複'abracadabra'

按名稱存取引數:

>>>'Coordinates:{latitude},{longitude}'.format(latitude='37.24N',longitude='-115.81W')'Coordinates: 37.24N, -115.81W'>>>coord={'latitude':'37.24N','longitude':'-115.81W'}>>>'Coordinates:{latitude},{longitude}'.format(**coord)'Coordinates: 37.24N, -115.81W'

存取引數的屬性:

>>>c=3-5j>>>('The complex number{0} is formed from the real part{0.real} '...'and the imaginary part{0.imag}.').format(c)'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'>>>classPoint:...def__init__(self,x,y):...self.x,self.y=x,y...def__str__(self):...return'Point({self.x},{self.y})'.format(self=self)...>>>str(Point(4,2))'Point(4, 2)'

存取引數的內容:

>>>coord=(3,5)>>>'X:{0[0]};  Y:{0[1]}'.format(coord)'X: 3;  Y: 5'

替換%s%r

>>>"repr() shows quotes:{!r}; str() doesn't:{!s}".format('test1','test2')"repr() shows quotes: 'test1'; str() doesn't: test2"

對齊文字以及指定寬度:

>>>'{:<30}'.format('left aligned')'left aligned                  '>>>'{:>30}'.format('right aligned')'                 right aligned'>>>'{:^30}'.format('centered')'           centered           '>>>'{:*^30}'.format('centered')# use '*' as a fill char'***********centered***********'

替換%+f%-f%f 以及指定正負號:

>>>'{:+f};{:+f}'.format(3.14,-3.14)# 總會顯示'+3.140000; -3.140000'>>>'{: f};{: f}'.format(3.14,-3.14)# 若為正數則顯示空格' 3.140000; -3.140000'>>>'{:-f};{:-f}'.format(3.14,-3.14)# 只顯示負號 -- 與 '{:f}; {:f}' 相同'3.140000; -3.140000'

替換%x%o 並將其值轉換為不同的進位制:

>>># format also supports binary numbers>>>"int:{0:d};  hex:{0:x};  oct:{0:o};  bin:{0:b}".format(42)'int: 42;  hex: 2a;  oct: 52;  bin: 101010'>>># with 0x, 0o, or 0b as prefix:>>>"int:{0:d};  hex:{0:#x};  oct:{0:#o};  bin:{0:#b}".format(42)'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'

使用逗號或底線作為數字分組分隔符號:

>>>'{:,}'.format(1234567890)'1,234,567,890'>>>'{:_}'.format(1234567890)'1_234_567_890'>>>'{:_b}'.format(1234567890)'100_1001_1001_0110_0000_0010_1101_0010'>>>'{:_x}'.format(1234567890)'4996_02d2'

表示為百分比:

>>>points=19>>>total=22>>>'Correct answers:{:.2%}'.format(points/total)'Correct answers: 86.36%'

作為特定型別格式:

>>>importdatetime>>>d=datetime.datetime(2010,7,4,12,15,58)>>>'{:%Y-%m-%d %H:%M:%S}'.format(d)'2010-07-04 12:15:58'

巢狀引數及更多複雜範例:

>>>foralign,textinzip('<^>',['left','center','right']):...'{0:{fill}{align}16}'.format(text,fill=align,align=align)...'left<<<<<<<<<<<<''^^^^^center^^^^^''>>>>>>>>>>>right'>>>>>>octets=[192,168,0,1]>>>'{:02X}{:02X}{:02X}{:02X}'.format(*octets)'C0A80001'>>>int(_,16)3232235521>>>>>>width=5>>>fornuminrange(5,12):...forbasein'dXob':...print('{0:{width}{base}}'.format(num,base=base,width=width),end=' ')...print()...    5     5     5   101    6     6     6   110    7     7     7   111    8     8    10  1000    9     9    11  1001   10     A    12  1010   11     B    13  1011

模板字串

模板字串提供如PEP 292 所述更簡單的字串替換。模板字串的主要用例是國際化 (i18n),因為在這種情況下,更簡單的語法和功能使得它比其他 Python 內建字串格式化工具更容易翻譯。基於模板字串建構的 i18n 函式庫範例,請參閱flufl.i18n 套件。

Template strings support$-based substitutions, using the following rules:

  • $$ is an escape; it is replaced with a single$.

  • $identifier names a substitution placeholder matching a mapping key of"identifier". By default,"identifier" is restricted to anycase-insensitive ASCII alphanumeric string (including underscores) thatstarts with an underscore or ASCII letter. The first non-identifiercharacter after the$ character terminates this placeholderspecification.

  • ${identifier} is equivalent to$identifier. It is required whenvalid identifier characters follow the placeholder but are not part of theplaceholder, such as"${noun}ification".

Any other appearance of$ in the string will result in aValueErrorbeing raised.

Thestring module provides aTemplate class that implementsthese rules. The methods ofTemplate are:

classstring.Template(template)

The constructor takes a single argument which is the template string.

substitute(mapping={},/,**kwds)

進行模板替換,並回傳一個新的字串。mapping 是任何有金鑰並符合模板裡佔位符號的字典型物件。或者如果關鍵字就是佔位符號時,你也可以改提供關鍵字引數。當mappingkwds 同時給定並存在重複時,kwds 的佔位符號會被優先使用。

safe_substitute(mapping={},/,**kwds)

類似於substitute(),但如果mappingkwds 中缺少佔位符號的話,原始的佔位符號會完整地出現在結果字串裡,而不會引發KeyError 例外。此外,與substitute() 不同的是,任何包含$ 的字句會直接回傳$ 而非引發ValueError

雖然仍可能發生其他例外,但這個方法被認為是「安全」的,因為它總是試圖回傳一個有用的字串而不是引發例外。從另一個角度來看,safe_substitute() 可能並非完全安全,因為它會默默忽略格式錯誤的模板,這些模板包含了多餘的左右定界符、不匹配的括號,或者不是有效的 Python 識別字的佔位符號。

is_valid()

如果模板有將導致substitute() 引發ValueError 的無效佔位符號,就會回傳False

在 3.11 版被加入.

get_identifiers()

回傳模板中有效識別字的串列,按照它們首次出現的順序,並忽略任何無效的識別字。

在 3.11 版被加入.

Template 實例也提供一個公開的資料屬性:

template

這是傳遞給建構函式template 引數的物件。一般來說,你不應該改變它,但並沒有強制設定成唯讀。

以下是如何使用 Template 的一個範例:

>>>fromstringimportTemplate>>>s=Template('$who likes $what')>>>s.substitute(who='tim',what='kung pao')'tim likes kung pao'>>>d=dict(who='tim')>>>Template('Give $who $100').substitute(d)Traceback (most recent call last):...ValueError:Invalid placeholder in string: line 1, col 11>>>Template('$who likes $what').substitute(d)Traceback (most recent call last):...KeyError:'what'>>>Template('$who likes $what').safe_substitute(d)'tim likes $what'

進階用法:你可以衍生Template 類別來自定義佔位符號語法、左右定界符字元,或者用於剖析模板字串的正規表示式。你可以透過覆寫這些類別屬性來達成:

  • delimiter -- 這是描述引入左右定界符的文字字串。預設值是$。請注意這不是正規表示式,因為實作會在需要時對這個字串呼叫re.escape()。也請注意你不能在建立類別後修改左右定界符。(意即在子類別的命名空間中必須設置不同的左右定界符)

  • idpattern -- This is the regular expression describing the pattern fornon-braced placeholders. The default value is the regular expression(?a:[_a-z][_a-z0-9]*). If this is given andbraceidpattern isNone this pattern will also apply to braced placeholders.

    備註

    Since defaultflags isre.IGNORECASE, pattern[a-z] can matchwith some non-ASCII characters. That's why we use the locala flaghere.

    在 3.7 版的變更:braceidpattern can be used to define separate patterns used inside andoutside the braces.

  • braceidpattern -- This is likeidpattern but describes the pattern forbraced placeholders. Defaults toNone which means to fall back toidpattern (i.e. the same pattern is used both inside and outside braces).If given, this allows you to define different patterns for braced andunbraced placeholders.

    在 3.7 版被加入.

  • flags -- The regular expression flags that will be applied when compilingthe regular expression used for recognizing substitutions. The default valueisre.IGNORECASE. Note thatre.VERBOSE will always be added to theflags, so customidpatterns must follow conventions for verbose regularexpressions.

    在 3.2 版被加入.

Alternatively, you can provide the entire regular expression pattern byoverriding the class attributepattern. If you do this, the value must be aregular expression object with four named capturing groups. The capturinggroups correspond to the rules given above, along with the invalid placeholderrule:

  • escaped -- 此群組與跳脫序列匹配,例如在預設模式下為$$

  • named -- 此群組與不帶大括號的佔位符號名稱匹配;它不應包含擷取群組中的左右定界符號。

  • braced -- 此群組與大括號括起來的佔位符號名稱匹配;它不應在擷取群組中包含左右定界符或大括號。

  • invalid -- 此群組與任何其他左右定界符模式(通常是單一左右定界符)匹配,且它應該出現在正規表示式的最後。

當此模式有匹配於模板但這些命名組中卻有任一個不匹配,此類別的方法將引發ValueError

輔助函式

string.capwords(s,sep=None)

使用str.split() 將引數分割為字詞,使用str.capitalize() 將每個單字大寫,並使用str.join() 將大寫字詞連接起來。如果可選的第二引數sep 不存在或為None,則連續的空白字元將替換為單一空格,並且刪除前導和尾隨空白;在其他情況下則使用sep 來分割和連接單字。