"string" --- 一般的な文字列操作
*******************************

**Source code:** Lib/string/__init__.py

======================================================================

参考:

  テキストシーケンス型 --- str

  文字列メソッド


文字列定数
==========

このモジュールで定義されている定数は以下の通りです:

string.ascii_letters

   後述の "ascii_lowercase" と "ascii_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

   String of ASCII characters which are considered printable by
   Python. This is a combination of "digits", "ascii_letters",
   "punctuation", and "whitespace".

   注釈:

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

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()" が文字列を文字としての文字データや置換フィールドに展
      開するために使用されます。

      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)

      与えられたフィールドの値を取り出します。 *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 に渡さ
      れる *args* と *kwargs* への参照です。使用されない引数の 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 and template string
literals, but it is less sophisticated and, in particular, does not
support arbitrary expressions in interpolations.

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

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

   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* を書くことができます。これは、置換される値の非デ
フォルトの書式を指定します。

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

*field_name* それ自身は、数かキーワードのいずれかである *arg_name* か
ら始まります。それが数である場合、位置引数を参照します。また、それがキ
ーワードである場合、指定されたキーワード引数を参照します。文字列に対し
て "str.isdecimal()" を呼び出した結果が真の場合、 *arg_name* は数とし
て扱われます。書式文字列中で数の arg_names が順に 0, 1, 2, ... である
場合、それらはすべて (いくつかではありません) 省略することができます。
そして数 0, 1, 2, ... は、自動的にその順で挿入されます。 *arg_name* は
引用符で区切られていないので、書式文字列内の任意の辞書キー (例えば文字
列 "'10'" や "':-]'" など) を指定することはできません。 *arg_name* の
後に任意の数のインデックス式または属性式を続けることができます。
"'.name'" 形式の式は "getattr()" を使用して指定された属性を選択します
。一方、 "'[index]'" 形式の式は "__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" are used within replacement fields contained
within a format string to define how individual values are presented
(see 書式指定文字列の文法, f-strings, and t-strings). They can also be
passed directly to the built-in "format()" function.  Each formattable
type may define how the format specification is to be interpreted.

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

一般的な取り決めとして、空の書式指定は、値に対して "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* 文字を付けることがで
きます。 この文字には任意の文字を指定でき、省略された場合はデフォルト
の空白文字となります。 formatted string literal の中や "str.format()"
メソッドを使う場合はリテラルの波括弧 (""{"" と ""}"") を *fill* 文字と
して使えないことに注意してください。 ただし、波括弧を入れ子になった置
換フィールド内に挿入することはできます。 この制限は "format()" 関数に
は影響しません。

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

+-----------+------------------------------------------------------------+
| オプショ  | 意味                                                       |
| ン        |                                                            |
|===========|============================================================|
| "'<'"     | 利用可能なスペースにおいて、左詰めを強制します (ほとんどの |
|           | オブジェクト においてのデフォルト)。                       |
+-----------+------------------------------------------------------------+
| "'>'"     | 利用可能なスペースにおいて、右詰めを強制します (いくつかの |
|           | オブジェクト においてのデフォルト)。                       |
+-----------+------------------------------------------------------------+
| "'='"     | 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.                                               |
+-----------+------------------------------------------------------------+
| "'^'"     | 利用可能なスペースにおいて、中央寄せを強制します。         |
+-----------+------------------------------------------------------------+

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

*sign* オプションは数値型に対してのみ有効であり、以下のうちのひとつと
なります:

+-----------+------------------------------------------------------------+
| オプショ  | 意味                                                       |
| ン        |                                                            |
|===========|============================================================|
| "'+'"     | Indicates that a sign should be used for both positive as  |
|           | well as negative numbers.                                  |
+-----------+------------------------------------------------------------+
| "'-'"     | Indicates that a sign should be used only for negative     |
|           | numbers (this is the default behavior).                    |
+-----------+------------------------------------------------------------+
| 空白      | Indicates that a leading space should be used on positive  |
|           | numbers, and a minus sign on negative numbers.             |
+-----------+------------------------------------------------------------+

"'z'" オプションはマイナス0の浮動小数点数をフォーマットの制度で丸めた
あとにプラス0に強制的に変換します。このオプションは浮動小数点数型に対
してのみ有効です。

バージョン 3.11 で変更: "'z'" オプションが追加されました (**PEP 682**
も参照)。

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

The *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.

When no explicit alignment is given, preceding the *width* field by a
zero ("'0'") character enables sign-aware zero-padding for numeric
types, excluding "complex".  This is equivalent to a *fill* character
of "'0'" with an *alignment* type of "'='".

バージョン 3.10 で変更: *width* フィールドに "'0'" を前置することは、
文字列に対するデフォルトの整列に影響を与えなくなりました。

*precision* は、表現型 "'f'" または "'F'" の場合小数点以下、表現型
"'g'" または "'G'" の場合は小数点以上と以下が何桁で表示されるべきかを
示す10進整数です。文字列の表現型の場合は最大フィールド幅、言い換えると
フィールドの内容から何文字が使用されるかを示します。*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.                                          |
+-----------+------------------------------------------------------------+
| "'_'"     | Inserts an underscore every 3 digits for integer           |
|           | presentation type "'d'" and floating-point presentation    |
|           | types, excluding "'n'". For integer presentation types     |
|           | "'b'", "'o'", "'x'", and "'X'", underscores are inserted   |
|           | every 4 digits. For other presentation types, this option  |
|           | is not supported.                                          |
+-----------+------------------------------------------------------------+

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.

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

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

   +-----------+------------------------------------------------------------+
   | 型        | 意味                                                       |
   |===========|============================================================|
   | "'s'"     | 文字列。これがデフォルトの値で、多くの場合省略されます。   |
   +-----------+------------------------------------------------------------+
   | None      | "'s'" と同じです。                                         |
   +-----------+------------------------------------------------------------+

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

   +-----------+------------------------------------------------------------+
   | 型        | 意味                                                       |
   |===========|============================================================|
   | "'b'"     | 2進数。出力される数値は2を基数とします。                   |
   +-----------+------------------------------------------------------------+
   | "'c'"     | 文字。数値を対応する Unicode 文字に変換します。            |
   +-----------+------------------------------------------------------------+
   | "'d'"     | 10進数。出力される数値は10を基数とします。                 |
   +-----------+------------------------------------------------------------+
   | "'o'"     | 8進数。出力される数値は8を基数とします。                   |
   +-----------+------------------------------------------------------------+
   | "'x'"     | 16進数。出力される数値は16を基数とします。 10進で9を超える |
   |           | 数字には 小文字が使われます。                              |
   +-----------+------------------------------------------------------------+
   | "'X'"     | 16進数。出力される数値は16を基数とします。10進で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'" と同じです。                                         |
   +-----------+------------------------------------------------------------+

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

利用可能な "float" と "Decimal" の表現型は以下です:

   +-----------+------------------------------------------------------------+
   | 型        | 意味                                                       |
   |===========|============================================================|
   | "'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'"     | 指数表記です。大文字の '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 "p=0", the decimal   |
   |           | point is omitted unless the "#" option is used.            |
   +-----------+------------------------------------------------------------+
   | "'F'"     | 固定小数点数表記です。"nan" が "NAN" に、"inf" が "INF" に |
   |           | 変換され ることを除き "'f'" と同じです。                   |
   +-----------+------------------------------------------------------------+
   | "'g'"     | 汎用表記です。与えられた精度 "p >= 1" に対して、この表記で |
   |           | は数値を 有効桁数 "p" に丸めた上で、数値の大きさに応じて固 |
   |           | 定小数点表記または 科学的表記で表します。精度 "0" は精度   |
   |           | "1" と同じものと取り扱われま す。  正確なルールは次の通り  |
   |           | です: 書式 "'e'" 型および精度 "p-1" 桁で数値 をフォーマッ  |
   |           | トした結果、指数部が "exp" になったと仮定します。このと き |
   |           | "m <= exp < p" ならば、数値は書式 "'f'" 型および精度       |
   |           | "p-1-exp" 桁でフォーマットされます。ただし "m" は浮動小数  |
   |           | 点数では -4 であり、 "Decimals" に対しては -6 です。それ以 |
   |           | 外の場合、数値は書式 "'e'" 型 および精度 "p-1" 桁でフォー  |
   |           | マットされます。どちらの場合でも、仮数部 の有効でない末尾  |
   |           | のゼロは取り除かれます。また小数点以下に表示する桁 が無い  |
   |           | 場合、 "'#'" オプションが使われた場合をのぞき、小数点は除  |
   |           | 去さ れます。  精度が指定されない場合、 "float" に対しては |
   |           | 有効桁数として "6" 桁を 適用します。  "Decimal" では、フォ |
   |           | ーマット結果の係数部は実際の値の 桁数によって決まります;   |
   |           | 絶対値が "1e-6" より小さい値や、最下位桁の 値が1より大きい |
   |           | 値では科学的表記が使われます。それ以外の場合は固定小 数点  |
   |           | 表記が使われます。  正と負の無限大と 0 および NaN は精度に |
   |           | 関係なくそれぞれ "inf", "-inf", "0", "-0" および "nan" と  |
   |           | なります。                                                 |
   +-----------+------------------------------------------------------------+
   | "'G'"     | 汎用フォーマットです。数値が大きくなったとき、 "'E'" に切  |
   |           | り替わるこ とを除き、 "'g'" と同じです。無限大と NaN の表  |
   |           | 示も大文字になります 。                                    |
   +-----------+------------------------------------------------------------+
   | "'n'"     | Number. This is the same as "'g'", except that it uses the |
   |           | current locale setting to insert the appropriate digit     |
   |           | group separators for the integral part of a number.        |
   +-----------+------------------------------------------------------------+
   | "'%'"     | パーセンテージです。数値は 100 倍され、固定小数点数フォー  |
   |           | マット ("'f'") でパーセント記号付きで表示されます。        |
   +-----------+------------------------------------------------------------+
   | None      | For "float" this is like the "'g'" type, except that when  |
   |           | fixed- point notation is used to format the result, it     |
   |           | always includes at least one digit past the decimal point, |
   |           | and switches to the scientific notation when "exp >= p -   |
   |           | 1".  When the precision is not specified, the latter will  |
   |           | be as large as needed to represent the given value         |
   |           | faithfully.  "Decimal" に対しては、現在の decimal コンテキ |
   |           | ストにおける "context.capitals" の値に応じて、 "'g'" か    |
   |           | "'G'" のどちらかと同じに なります。  全体として、他の書式  |
   |           | 修正指定によって変更された "str()" の出力に一致 するような |
   |           | 結果になります。                                           |
   +-----------+------------------------------------------------------------+

The result should be correctly rounded to a given precision "p" of
digits after the decimal point.  The rounding mode for "float" matches
that of the "round()" builtin.  For "Decimal", the rounding mode of
the current context will be used.

The available presentation types for "complex" are the same as those
for "float" ("'%'" is not allowed).  Both the real and imaginary
components of a complex number are formatted as floating-point
numbers, according to the specified presentation type.  They are
separated by the mandatory sign of the imaginary part, the latter
being terminated by a "j" suffix.  If the presentation type is
missing, the result will match the output of "str()" (complex numbers
with a non-zero real part are also surrounded by parentheses),
possibly altered by 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'

Using the comma or the underscore as a digit group separator:

   >>> '{:,}'.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'
   >>> '{:_}'.format(123456789.123456789)
   '123_456_789.12345679'
   >>> '{:.,}'.format(123456789.123456789)
   '123456789.123,456,79'
   >>> '{:,._}'.format(123456789.123456789)
   '123,456,789.123_456_79'

パーセントを表示する:

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


Template strings ($-strings)
============================

注釈:

  The feature described here was introduced in Python 2.4; a simple
  templating method based upon regular expressions. It predates
  "str.format()", formatted string literals, and template string
  literals.It is unrelated to template string literals (t-strings),
  which were introduced in Python 3.14. These evaluate to
  "string.templatelib.Template" objects, found in the
  "string.templatelib" module.

テンプレート文字列では **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* はテンプレート中のプレースホルダに対応するキーを持つよ
      うな任意の辞書類似オブジェクトです。辞書を指定する代わりに、キー
      ワード引数も指定でき、その場合にはキーワードをプレースホルダ名に
      対応させます。*mapping* と *kwds* の両方が指定され、内容が重複し
      た場合には、*kwds* に指定したプレースホルダを優先します。

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

      "substitute()" と同じですが、プレースホルダに対応するものを
      *mapping* や *kwds* から見つけられなかった場合に、 "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".

      Added in version 3.11.

   get_identifiers()

      テンプレート内の有効な識別子のリストを、その識別子が最初に現れる
      順番で返します。不正な識別子は無視されます。

      Added in version 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* -- これは波括弧なしのプレースホルダーを記述する正規表現
  です。デフォルト値は正規表現 "(?a:[_a-z][_a-z0-9]*)" です。
  *idpattern* が与えられており、かつ *braceidpattern* が "None" の場合
  、このパターンは波括弧付きのプレースホルダーにも適用されます。

  注釈:

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

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

* *braceidpattern* -- これは *idpattern* に似ていますが、波括弧付きプ
  レースホルダーのパターンを記述します。デフォルトは "None" で、
  *idpattern* が適用されます (すなわち、波括弧の内側と外側の両方に同じ
  パターンが使われます) 。 *braceidpattern* を使うと、波括弧付きと波括
  弧なしのプレースホルダーにそれぞれ異なるパターンを定義することができ
  ます。

  Added in version 3.7.

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

  Added in version 3.2.

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

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

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

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

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

このクラスのメソッドは、これらの名前付きグループに1つもマッチすること
なくパターンがテンプレートにマッチした場合、 "ValueError" を送出します
。


ヘルパー関数
============

string.capwords(s, sep=None)

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