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 ロケールにおいて、区切り文字 (punctuation characters) として扱われる ASCII 文字の文字列です: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~.

string.printable

印刷可能な ASCII 文字で構成される文字列です。 digits, ascii_letters, punctuation および whitespace を組み合わせたものです。

string.whitespace

空白 (whitespace) として扱われる ASCII 文字全てを含む文字列です。ほとんどのシステムでは、これはスペース (space)、タブ (tab)、改行 (linefeed)、復帰 (return)、改頁 (formfeed)、垂直タブ (vertical tab) です。

カスタムの文字列書式化

組み込みの文字列 (string) クラスには、 PEP 3101 で記述されている format() メソッドによって複雑な変数置換と値のフォーマットを行う機能があります。 string モジュールの Formatter クラスでは、組み込みの format() メソッドと同じ実装を使用して、独自の文字列フォーマットの振る舞いを作成してカスタマイズすることができます。

class string.Formatter

Formatter クラスは、以下のメソッドを持ちます:

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

主要な API メソッドです。書式文字列と、任意の位置引数およびキーワード引数のセットを取ります。これは、vformat() を呼び出す単なるラッパーです。

バージョン 3.7 で変更: 書式文字列は 位置専用 の引数となりました。

vformat(format_string, args, kwargs)

この関数はフォーマットの実際の仕事をします。この関数は、 *args および **kwargs シンタックスを使用して、辞書を個々の引数として unpack してから再度 pack するのではなく、引数としてあらかじめ用意した辞書を渡したい場合のために、独立した関数として公開されます。 vformat() は、書式文字列を文字データと置換フィールドに分解する仕事をします。それは、以下に記述する様々なメソッドを呼び出します。

さらに、 Formatter ではサブクラスによって置き換えられることを意図した次のようないくつかのメソッドが定義されています。

parse(format_string)

format_stringを探査し、タプル、 (literal_text, field_name, format_spec, conversion) のイテラブルを返します。これは vformat() が文字列を文字としての文字データや置換フィールドに展開するために使用されます。

タプルの値は、概念的に文字としての文字データと、それに続く単一の置換フィールドを表現します。文字としての文字データが無い場合は (ふたつの置換フィールドが連続した場合などに起き得ます) 、 literal_text は長さが 0 の文字列となります。置換フィールドが無い場合は、 field_name, format_spec および conversionNone となります。

get_field(field_name, args, kwargs)

引数として与えた parse() (上記参照) により返される field_name を書式指定対象オブジェクトに変換します。返り値はタプル、 (obj, used_key) です。デフォルトでは PEP 3101 に規定される "0[name]" や "label.title" のような形式の文字列を引数としてとります。 argskwargsvformat() に渡されます。返り値 used_key は、 get_value()key 引数と同じ意味を持ちます。

get_value(key, args, kwargs)

与えられたフィールドの値を取り出します。 key 引数は整数でも文字列でも構いません。整数の場合は、位置引数 args のインデックス番号を示します。文字列の場合は、名前付きの引数 kwargs を意味します。

args 引数は、 vformat() への位置引数のリストに設定され、 kwargs 引数は、キーワード引数の辞書に設定されます。

フィールド名が (ピリオドで区切られた) いくつかの要素からなっている場合、最初の要素のみがこれらの関数に渡されます。残りの要素に関しては、通常の属性またはインデックスアクセスと同様に処理されます。

つまり、例えば、フィールドが '0.name' と表現されるとき、 get_value() は、 key 引数が 0 として呼び出されます。属性 name は、組み込みの getattr() 関数が呼び出され、 get_value() が返されたのちに検索されます。

インデックスまたはキーワードが存在しないアイテムを参照した場合、 IndexError または KeyError が送出されます。

check_unused_args(used_args, args, kwargs)

希望に応じて未使用の引数がないか確認する機能を実装します。この関数への引数は、書式指定文字列で実際に参照されるすべての引数のキーの set (位置引数の整数、名前付き引数の文字列) と、vformat に渡される argskwargs への参照です。使用されない引数の set は、これらのパラメータから計算されます。 check_unused_args() は、確認の結果が偽である場合に例外を送出するものとみなされます。

format_field(value, format_spec)

format_field() は単純に組み込みのグローバル関数 format() を呼び出します。このメソッドは、サブクラスをオーバーライドするために提供されます。

convert_field(value, conversion)

(get_field() が返す) 値を (parse() メソッドが返すタプルの形式で) 与えられた変換タイプとして変換します。デフォルトバージョンは 's' (str), 'r' (repr), 'a' (ascii) 変換タイプを理解します。

書式指定文字列の文法

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, but it is less sophisticated and, in particular, does not support arbitrary expressions.

書式指定文字列は波括弧 {} に囲まれた "置換フィールド" を含みます。波括弧に囲まれた部分以外は全て単純な文字として扱われ、変更を加えることなく出力へコピーされます。波括弧を文字として扱う必要がある場合は、二重にすることでエスケープすることができます: {{ および }}

置換フィールドの文法は以下です:

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

もっと簡単にいうと、置換フィールドは field_name で始められます。これによって指定したオブジェクトの値が、置換フィールドの代わりに書式化され出力に挿入されます。field_name の後に、感嘆符 '!' を挟んで conversion フィールドを続けることができます。最後にコロン ':' を挟んで、 format_spec を書くことができます。これは、置換される値の非デフォルトの書式を指定します。

書式指定ミニ言語仕様 節も参照して下さい。

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 で変更: str.format() を使い、位置引数指定を省略することができます。 '{} {}'.format(a, b)'{0} {1}'.format(a, b) と同じになります。

バージョン 3.4 で変更: Formatter を使い、位置引数指定を省略することができます。

簡単な書式指定文字列の例を挙げます:

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

置換 (conversion) フィールドにより書式変換前に型の強制変換が実施されます。通常、値の書式変換は __format__() によって実施されます。しかしながら、場合によっては、文字列として変換することを強制したり、書式指定の定義をオーバーライドしたくなることもあります。 __format__() の呼び出し前に値を文字列に変換すると、通常の書式変換の処理は飛ばされます。

現在 3つの変換フラグがサポートされています: 値に対して str() を呼ぶ '!s'repr() を呼ぶ '!r'ascii() を呼ぶ '!a'

いくつかの例です:

"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 フィールドは、フィールド幅、文字揃え、埋め方、精度などの、値を表現する仕様を含みます。それぞれの値の型は、 "formatting mini-language" 、または、 format_spec の実装で定義されます。

ほとんどの組み込み型は、次のセクションに記載された共通の formatting mini-language をサポートします。

format_spec フィールド内には入れ子になった置換フィールドを含めることもできます。入れ子になった置換フィールドにはフィールド名、変換フラグ、書式指定を含めることができますが、さらに入れ子の階層を含めることはできません。 format_spec 中の置換フィールドは format_spec 文字列が解釈される前に置き換えられます。これにより、値の書式を動的に指定することができます。

書式指定例 のいくつかの例も参照して下さい。

書式指定ミニ言語仕様

書式指定 ("Format specifications") は書式指定文字列の個々の値を表現する方法を指定するための、置換フィールドで使用されます (書式指定文字列の文法 および f-strings を参照してください) 。 それらは、組み込み関数の format() 関数に直接渡されます。 それぞれの書式指定可能な型について、書式指定がどのように解釈されるかが規定されます。

多くの組み込み型は、書式指定に関して以下のオプションを実装します。しかしながら、いくつかの書式指定オプションは数値型でのみサポートされます。

一般的な取り決めとして、空の書式指定は、値に対して str() を呼び出したときと同じ結果を与えます。通常、空でない書式指定はその結果を変更します。

一般的な書式指定子 (standard format specifier) の書式は以下です:

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

有効な align 値を指定する場合、その前に fill 文字を付けることができます。 この文字には任意の文字を指定でき、省略された場合はデフォルトの空白文字となります。 formatted string literal の中や str.format() メソッドを使う場合はリテラルの波括弧 ("{" と "}") を fill 文字として使えないことに注意してください。 ただし、波括弧を入れ子になった置換フィールド内に挿入することはできます。 この制限は format() 関数には影響しません。

様々な align オプションの意味は以下のとおりです:

オプション

意味

'<'

利用可能なスペースにおいて、左詰めを強制します (ほとんどのオブジェクトにおいてのデフォルト)。

'>'

利用可能なスペースにおいて、右詰めを強制します (いくつかのオブジェクトにおいてのデフォルト)。

'='

符号 (があれば) の後ろを埋めます。 '+000000120' のような形で表示されます。このオプションは数値型に対してのみ有効です。フィールド幅の直前が '0' の時はこれがデフォルトの数値になります。

'^'

利用可能なスペースにおいて、中央寄せを強制します。

最小のフィールド幅が定義されない限り、フィールド幅はデータを表示するために必要な幅と同じになることに注意して下さい。そのため、その場合には、 align オプションは意味を持ちません。

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 も参照)。

'#' オプションは、変換に「別形式」を使用します。別形式は、異なる型に対して違った風に定義されます。このオプションは、整数、浮動小数点数、複素数でのみ有効です。整数に対して2進法、8進法、または16進法の出力が使用される場合、このオプションは出力される値にそれぞれ '0b', '0o', '0x', '0X' 接頭辞を加えます。浮動小数点数、複素数については、別形式では、小数点文字の後に数字がなくても変換結果には常に小数点文字が含まれます。通常は、数字が続く場合にのみ小数点文字がこれらの変換結果に現われます。さらに、'g''G' の変換については、最後の 0 は結果から取り除かれません。

',' オプションは、千の位のセパレータにカンマを使うことを合図します。ロケール依存のセパレータには、代わりに 'n' の整数表現形式を使ってください。

バージョン 3.1 で変更: ',' オプションが追加されました (PEP 378 も参照)。

'_' オプションは、浮動小数点数の表現型と整数の表現型 'd' における千倍ごとの区切り文字にアンダースコアを使うというしるしです。 整数の表現型の 'b', 'o', 'x', 'X' では、4桁ごとにアンダースコアが挿入されます。 他の表現型でこのオプションを指定するとエラーになります。

バージョン 3.6 で変更: '_' オプションが追加されました (PEP 515 も参照)。

width is a decimal integer defining the minimum total field width, including any prefixes, separators, and other formatting characters. If not specified, then the field width will be determined by the content.

alignment が明示的に与えられない場合、 width フィールドにゼロ ('0') 文字を前置することは、数値型のための符号を意識した 0 パディングを可能にします。これは fill 文字に '0' を指定して、 alignment タイプに '=' を指定したことと等価です。

バージョン 3.10 で変更: Preceding the width field by '0' no longer affects the default alignment for strings.

The precision is a decimal integer indicating how many digits should be displayed after the decimal point for presentation types 'f' and 'F', or before and after the decimal point for presentation types 'g' or 'G'. For string presentation types the field indicates the maximum field size - in other words, how many characters will be used from the field content. The precision is not allowed for integer presentation types.

最後に、type は、データがどのように表現されるかを決定します。

利用可能な文字列の表現型は以下です:

意味

's'

文字列。これがデフォルトの値で、多くの場合省略されます。

None

's' と同じです。

利用可能な整数の表現型は以下です:

意味

'b'

2進数。出力される数値は2を基数とします。

'c'

文字。数値を対応する Unicode 文字に変換します。

'd'

10進数。出力される数値は10を基数とします。

'o'

8進数。出力される数値は8を基数とします。

'x'

16進数。出力される数値は16を基数とします。 10進で9を超える数字には小文字が使われます。

'X'

Hex format. Outputs the number in base 16, using upper-case letters for the digits above 9. In case '#' is specified, the prefix '0x' will be upper-cased to '0X' as well.

'n'

数値。現在のロケールに従い、区切り文字を挿入することを除けば、 'd' と同じです。

None

'd' と同じです。

これらの表現型に加えて、整数は ('n'None を除く) 以下の浮動小数点数の表現型で書式指定できます。 そうすることで整数は書式変換される前に float() を使って浮動小数点数に変換されます。

利用可能な floatDecimal の表現型は以下です:

意味

'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 no digits follow the decimal point, the decimal point is also removed unless the # option is used.

'E'

指数表記です。大文字の 'E' を使うことを除いては、 'e' と同じです。

'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 no digits follow the decimal point, the decimal point is also removed unless the # option is used.

'F'

固定小数点数表記です。nanNAN に、infINF に変換されることを除き 'f' と同じです。

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

With no precision given, uses a precision of 6 significant digits for float. For Decimal, the coefficient of the result is formed from the coefficient digits of the value; scientific notation is used for values smaller than 1e-6 in absolute value and values where the place value of the least significant digit is larger than 1, and fixed-point notation is used otherwise.

正と負の無限大と 0 および NaN は精度に関係なくそれぞれ inf, -inf, 0, -0 および nan となります。

'G'

汎用フォーマットです。数値が大きくなったとき、 'E' に切り替わることを除き、 'g' と同じです。無限大と NaN の表示も大文字になります。

'n'

数値です。現在のロケールに合わせて、数値分割文字が挿入されることを除き、 'g' と同じです。

'%'

パーセンテージです。数値は 100 倍され、固定小数点数フォーマット ('f') でパーセント記号付きで表示されます。

None

For float this is the same as 'g', except that when fixed-point notation is used to format the result, it always includes at least one digit past the decimal point. The precision used is as large as needed to represent the given value faithfully.

For Decimal, this is the same as either 'g' or 'G' depending on the value of context.capitals for the current decimal context.

The overall effect is to match the output of str() as altered by the other 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')      # unpacking argument sequence
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated
'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.'
>>> class Point:
...     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)  # show it always
'+3.140000; -3.140000'
>>> '{: f}; {: f}'.format(3.14, -3.14)  # show a space for positive numbers
' 3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14)  # show only the minus -- same as '{: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'

パーセントを表示する:

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

型特有の書式指定を使う:

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

引数をネストする、さらに複雑な例:

>>> for align, text in zip('<^>', ['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
>>> for num in range(5,12): 
...     for base in '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 にある他の組み込みの文字列フォーマット機能よりも翻訳がしやすいからです。 テンプレート文字列の上に構築された国際化のためのライプラリの例として、 flufl.i18n を調べてみてください。

テンプレート文字列は $ に基づいた置換をサポートしていて、次の規則が使われています:

  • $$ はエスケープ文字です; $ 一つに置換されます。

  • $identifier"identifier" のマッピングキーに合致する置換プレースホルダーを指定します。デフォルトでは、 "identifier" は大文字と小文字を区別しない ASCII 英数字 (アンダースコアを含む) からなら文字列に制限されています。文字列はアンダースコアか ASCII 文字から始まるものでなければなりません。$ の後に識別子に使えない文字が出現すると、そこでプレースホルダ名の指定が終わります。

  • ${identifier}$identifier と同じです。プレースホルダ名の後ろに識別子として使える文字列が続いていて、それをプレースホルダ名の一部として扱いたくない場合、例えば "${noun}ification" のような場合に必要な書き方です。

上記以外の書き方で文字列中に $ を使うと ValueError を送出します。

string モジュールでは、上記のような規則を実装した Template クラスを提供しています。 Template のメソッドを以下に示します:

class string.Template(template)

コンストラクタはテンプレート文字列になる引数を一つだけ取ります。

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

テンプレート置換を行い、新たな文字列を生成して返します。mapping はテンプレート中のプレースホルダに対応するキーを持つような任意の辞書類似オブジェクトです。辞書を指定する代わりに、キーワード引数も指定でき、その場合にはキーワードをプレースホルダ名に対応させます。mappingkwds の両方が指定され、内容が重複した場合には、kwds に指定したプレースホルダを優先します。

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

substitute() と同じですが、プレースホルダに対応するものを mappingkwds から見つけられなかった場合に、 KeyError 例外を送出する代わりにもとのプレースホルダがそのまま入ります。また、 substitute() とは違い、規則外の書き方で $ を使った場合でも、 ValueError を送出せず単に $ を返します。

その他の例外も発生し得る一方で、このメソッドが「安全 (safe) 」と呼ばれているのは、置換操作は常に、例外を送出する代わりに利用可能な文字列を返そうとするからです。別の見方をすれば、 safe_substitute() は区切り間違いによるぶら下がり (dangling delimiter) や波括弧の非対応、 Python の識別子として無効なプレースホルダ名を含むような不正なテンプレートを何も警告せずに無視するため、安全とはいえないのです。

is_valid()

Returns false if the template has invalid placeholders that will cause substitute() to raise ValueError.

バージョン 3.11 で追加.

get_identifiers()

Returns a list of the valid identifiers in the template, in the order they first appear, ignoring any invalid identifiers.

バージョン 3.11 で追加.

Template のインスタンスは、次のような public な属性を提供しています:

template

コンストラクタの引数 template に渡されたオブジェクトです。通常、この値を変更すべきではありませんが、読み出し専用アクセスを強制しているわけではありません。

Templateの使い方の例を以下に示します:

>>> from string import Template
>>> 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() を呼び出すので、正規表現になってしまうような文字列にしては なりません 。 さらにクラスを作成した後に delimiter を変更できない (つまり、別の delimiter を設定したいのであれば、サブクラスの名前空間で行わなければならない) ことに注意してください。

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

    注釈

    flags のデフォルトは re.IGNORECASE なので、 [a-z] というパターンはいくつかの非 ASCII 文字に適合できます。 そのため、ここではローカルの a フラグを使っています。

    バージョン 3.7 で変更: braceidpattern を使用すると、中括弧の内側と外側で使用する別々のパターンを定義できます。

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

    バージョン 3.7 で追加.

  • flags -- 代入の認識のために使用される正規表現をコンパイルする際に適用される正規表現フラグ。デフォルト値は re.IGNORECASE です。re.VERBOSE が常にフラグに追加されるということに注意してください。したがって、カスタムな idpattern は verbose 正規表現の規約に従わなければなりません。

    バージョン 3.2 で追加.

他にも、クラス属性 pattern をオーバライドして、正規表現パターン全体を指定できます。オーバライドを行う場合、 pattern の値は 4 つの名前つきキャプチャグループ (capturing group) を持った正規表現オブジェクトでなければなりません。これらのキャプチャグループは、上で説明した規則と、無効なプレースホルダに対する規則に対応しています:

  • escaped -- このグループはエスケープシーケンス、すなわちデフォルトパターンにおける $$ に対応します。

  • named -- このグループは波括弧でくくらないプレースホルダ名に対応します; キャプチャグループに区切り文字を含めてはなりません。

  • braced -- このグループは波括弧でくくったプレースホルダ名に対応します; キャプチャグループに区切り文字を含めてはなりません。

  • invalid -- このグループはそのほかの区切り文字のパターン (通常は区切り文字一つ) に対応し、正規表現の末尾に出現しなければなりません。

The methods on this class will raise ValueError if the pattern matches the template without one of these named groups matching.

ヘルパー関数

string.capwords(s, sep=None)

str.split() を使って引数を単語に分割し、 str.capitalize() を使ってそれぞれの単語の先頭の文字を大文字に変換し、 str.join() を使ってつなぎ合わせます。オプションの第2引数 sep が与えられないか None の場合、この置換処理は文字列中の連続する空白文字をスペース一つに置き換え、先頭と末尾の空白を削除します、それ以外の場合には sep は split と join に使われます。