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

**ソースコード:** Lib/string.py

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

The "string" module contains a number of useful constants and classes,
as well as some deprecated legacy functions that are also available as
methods on strings. In addition, Python’s built-in string classes
support the sequence type methods described in the Sequence Types —
str, unicode, list, tuple, bytearray, buffer, xrange section, and also
the string-specific methods described in the 文字列メソッド section.
To output formatted strings use template strings or the "%" operator
described in the String Formatting Operations section. Also, see the
"re" module for string functions based on regular expressions.


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

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

string.ascii_letters

   後述の "ascii_lowercase" と "ascii_uppercase" を合わせたもの。この
   値はロケールに依存しません。

string.ascii_lowercase

   小文字 "'abcdefghijklmnopqrstuvwxyz'" 。この値はロケールに依存せず
   、固定です。

string.ascii_uppercase

   大文字 "'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" 。この値はロケールに依存せず
   、固定です。

string.digits

   文字列 "'0123456789'" です。

string.hexdigits

   文字列 "'0123456789abcdefABCDEF'" です。

string.letters

   The concatenation of the strings "lowercase" and "uppercase"
   described below.  The specific value is locale-dependent, and will
   be updated when "locale.setlocale()" is called.

string.lowercase

   A string containing all the characters that are considered
   lowercase letters. On most systems this is the string
   "'abcdefghijklmnopqrstuvwxyz'".  The specific value is locale-
   dependent, and will be updated when "locale.setlocale()" is called.

string.octdigits

   文字列 "'01234567'" です。

string.punctuation

   "C" ロケールにおいて、句読点として扱われる ASCII 文字の文字列です。

string.printable

   String of characters which are considered printable.  This is a
   combination of "digits", "letters", "punctuation", and
   "whitespace".

string.uppercase

   A string containing all the characters that are considered
   uppercase letters. On most systems this is the string
   "'ABCDEFGHIJKLMNOPQRSTUVWXYZ'".  The specific value is locale-
   dependent, and will be updated when "locale.setlocale()" is called.

string.whitespace

   A string containing all characters that are considered whitespace.
   On most systems this includes the characters space, tab, linefeed,
   return, formfeed, and vertical tab.


カスタムの文字列書式化
======================

バージョン 2.6 で追加.

The built-in str and unicode classes provide the ability to do complex
variable substitutions and value formatting via the "str.format()"
method described in **PEP 3101**.  The "Formatter" class in the
"string" module allows you to create and customize your own string
formatting behaviors using the same implementation as the built-in
"format()" method.

class string.Formatter

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

   format(format_string, *args, **kwargs)

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

   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* および *conversion* が
      "None" となります。

   get_field(field_name, args, kwargs)

      引数として与えた "parse()" (上記参照) により返される
      *field_name* を書式指定対象オブジェクトに変換します。返り値はタ
      プル、 (obj, used_key) です。デフォルトでは **PEP 3101** に規定
      される 「0[name]」 や 「label.title」 のような形式の文字列を引数
      としてとります。 *args* と *kwargs* は "vformat()" に渡されます
      。返り値 *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
      に渡される *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).

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

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

      replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
      field_name        ::= arg_name ("." attribute_name | "[" element_index "]")*
      arg_name          ::= [identifier | integer]
      attribute_name    ::= identifier
      element_index     ::= integer | index_string
      index_string      ::= <any source character except "]"> +
      conversion        ::= "r" | "s"
      format_spec       ::= <described in the next section>

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

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

*field_name* それ自身は、数かキーワードのいずれかである *arg_name* か
ら始まります。それが数である場合、位置引数を参照します。また、それがキ
ーワードである場合、指定されたキーワード引数を参照します。書式文字列中
で数の arg_names が順に 0, 1, 2, … である場合、それらはすべて (いくつ
かではありません) 省略することができます。そして数 0, 1, 2, … は、自動
的にその順で挿入されます。 *arg_name* は引用符で区切られていないので、
書式文字列内の任意の辞書キー (例えば文字列 "'10'" や "':-]'" など) を
指定することはできません。 *arg_name* の後に任意の数のインデックス式ま
たは属性式を続けることができます。 "'.name'" 形式の式は "getattr()" を
使用して指定された属性を選択します。一方、 "'[index]'" 形式の式は
"__getitem__()" を使用してインデックス参照を行います。

バージョン 2.7 で変更: 位置引数指定を省略することができます。"'{} {}'"
は "'{0} {1}'" と同じになります。

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

   "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__()" の呼び
出し前に値を文字列に変換すると、通常の書式変換の処理は飛ばされます。

Two conversion flags are currently supported: "'!s'" which calls
"str()" on the value, and "'!r'" which calls "repr()".

いくつかの例です:

   "Harold's a clever {0!s}"        # Calls str() on the argument first
   "Bring out the holy {name!r}"    # Calls repr() 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 書式指定文字列の文法).  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 ::= [[fill]align][sign][#][0][width][,][.precision][type]
   fill        ::= <any character>
   align       ::= "<" | ">" | "=" | "^"
   sign        ::= "+" | "-" | " "
   width       ::= integer
   precision   ::= integer
   type        ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

If a valid *align* value is specified, it can be preceded by a *fill*
character that can be any character and defaults to a space if
omitted. It is not possible to use a literal curly brace (「"{"」 or
「"}"」) as the *fill* character when using the "str.format()" method.
However, it is possible to insert a curly brace with a nested
replacement field.  This limitation doesn’t affect the "format()"
function.

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

   +-----------+------------------------------------------------------------+
   | オプショ  | 意味                                                       |
   | ン        |                                                            |
   +===========+============================================================+
   | "'<'"     | 利用可能なスペースにおいて、左詰めを強制します (ほとんどの |
   |           | オブジェ クトにおいてのデフォルト)。                       |
   +-----------+------------------------------------------------------------+
   | "'>'"     | 利用可能なスペースにおいて、右詰めを強制します (いくつかの |
   |           | オブジェ クトにおいてのデフォルト)。                       |
   +-----------+------------------------------------------------------------+
   | "'='"     | 符号 (があれば) の後ろを埋めます。 『+000000120』 のような |
   |           | 形で表示 されます。このオプションは数値型に対してのみ有効  |
   |           | です。フィールド幅 の直前が 『0』 の時はこれがデフォルトに |
   |           | なります。                                                 |
   +-----------+------------------------------------------------------------+
   | "'^'"     | 利用可能なスペースにおいて、中央寄せを強制します。         |
   +-----------+------------------------------------------------------------+

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

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

   +-----------+------------------------------------------------------------+
   | オプショ  | 意味                                                       |
   | ン        |                                                            |
   +===========+============================================================+
   | "'+'"     | 符号の使用を、正数、負数の両方に対して指定します。         |
   +-----------+------------------------------------------------------------+
   | "'-'"     | 符号の使用を、負数に対してのみ指定します (デフォルトの挙動 |
   |           | です)。                                                    |
   +-----------+------------------------------------------------------------+
   | 空白      | 空白を正数の前に付け、負号を負数の前に使用することを指定し |
   |           | ます。                                                     |
   +-----------+------------------------------------------------------------+

The "'#'" option is only valid for integers, and only for binary,
octal, or hexadecimal output.  If present, it specifies that the
output will be prefixed by "'0b'", "'0o'", or "'0x'", respectively.

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

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

*width* は10進数の整数で、最小のフィールド幅を定義します。指定されない
場合、フィールド幅はその内容により決定されます。

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

*precision* は10進数で、"'f'" および "'F'" で指定される浮動小数点数の
小数点以下、あるいは "'g'" および "'G'" で指定される浮動小数点数の小数
点の前後に表示される桁数を指定します。非数型に対しては、最大フィールド
幅を表します。言い換えると、フィールドの内容から何文字を使用するかとい
うことです。*precision* は整数型に対しては使うことができません。

最後に、*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を越える |
   |           | 数字には 大文字が使われます。                              |
   +-----------+------------------------------------------------------------+
   | "'n'"     | 数値。現在のロケールに従い、区切り文字を挿入することを除け |
   |           | ば、 "'d'" と同じです。                                    |
   +-----------+------------------------------------------------------------+
   | None      | "'d'" と同じです。                                         |
   +-----------+------------------------------------------------------------+

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

利用可能な浮動小数点数と10進数の表現型は以下です:

   +-----------+------------------------------------------------------------+
   | 型        | 意味                                                       |
   +===========+============================================================+
   | "'e'"     | 指数表記です。指数を示す 『e』 を使って数値を表示します。  |
   |           | デフォルト の精度は "6" です。                             |
   +-----------+------------------------------------------------------------+
   | "'E'"     | 指数表記です。大文字の 『E』 を使うことを除いては、 "'e'"  |
   |           | と同じで す。                                              |
   +-----------+------------------------------------------------------------+
   | "'f'"     | 固定小数点数です。数値を固定小数点数として表示します。デフ |
   |           | ォルトの 精度は "6" です。                                 |
   +-----------+------------------------------------------------------------+
   | "'F'"     | Fixed point. Same as "'f'".                                |
   +-----------+------------------------------------------------------------+
   | "'g'"     | 汎用フォーマットです。精度を "p >= 1" の数値で与えた場合、 |
   |           | 数値を有 効桁 "p" で丸め、桁に応じて固定小数点か指数表記で |
   |           | 表示します。  精度のルールは以下のように決まっています: 書 |
   |           | 式指定の結果が "'e'" 型 で "p-1" の精度の場合、指数は      |
   |           | "exp" になると仮定します。そうすると 、 "-4 <= exp < p" の |
   |           | とき数値は表現型 "'f'" で精度 "p-1-exp" に書式 変換されま  |
   |           | す。それ以外の場合、数値は "'e'" 型で精度 "p-1" に書式指   |
   |           | 定されます。この両方の場合で重要でない、連続した 0 は取り  |
   |           | 除かれます , そして残った桁が無い場合小数点は取り除かれま  |
   |           | す。  正と負の無限大と 0 および NaN は精度に関係なくそれぞ |
   |           | れ "inf", "-inf", "0", "-0" および "nan" となります。  "0" |
   |           | の精度は "1" の精度と同等に扱われます。デフォルトの精度は  |
   |           | "6" です。                                                 |
   +-----------+------------------------------------------------------------+
   | "'G'"     | 汎用フォーマットです。数値が大きくなったとき、 "'E'" に切  |
   |           | り替わるこ とを除き、 "'g'" と同じです。無限大と NaN の表  |
   |           | 示も大文字になります 。                                    |
   +-----------+------------------------------------------------------------+
   | "'n'"     | 数値です。現在のロケールに合わせて、数値分割文字が挿入され |
   |           | ることを 除き、 "'g'" と同じです。                         |
   +-----------+------------------------------------------------------------+
   | "'%'"     | パーセンテージです。数値は 100 倍され、固定小数点数フォー  |
   |           | マット ("'f'") でパーセント記号付きで表示されます。        |
   +-----------+------------------------------------------------------------+
   | None      | The same as "'g'".                                         |
   +-----------+------------------------------------------------------------+


書式指定例
----------

この節では、 "str.format()" 構文の例を紹介し、さらに従来の "%"-書式と
比較します。

多くの場合、新構文に "{}" を加え、 "%" の代わりに ":" を使うことで、古
い "%"-書式に類似した書式になります。例えば、"'%03.2f'" は
"'{:03.2f}'" と変換できます。

以下の例で示すように、新構文はさらに新たに様々なオプションもサポートし
ています。

位置引数を使ったアクセス:

   >>> '{0}, {1}, {2}'.format('a', 'b', 'c')
   'a, b, c'
   >>> '{}, {}, {}'.format('a', 'b', 'c')  # 2.7+ 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(object):
   ...     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.5
   >>> total = 22
   >>> 'Correct answers: {:.2%}'.format(points/total)
   'Correct answers: 88.64%'

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

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


テンプレート文字列
==================

バージョン 2.4 で追加.

テンプレート (template) を使うと、 **PEP 292** で解説されているように
より簡潔に文字列置換 (string substitution) を行えるようになります。通
常の "%" ベースの置換に代わって、テンプレートでは以下のような規則に従
った "$" ベースの置換をサポートしています:

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

* "$identifier" names a substitution placeholder matching a mapping
  key of ""identifier"".  By default, ""identifier"" must spell a
  Python identifier.  The first non-identifier character after the "$"
  character terminates this placeholder specification.

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

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

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

class string.Template(template)

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

   substitute(mapping[, **kws])

      Performs the template substitution, returning a new string.
      *mapping* is any dictionary-like object with keys that match the
      placeholders in the template.  Alternatively, you can provide
      keyword arguments, where the keywords are the placeholders.
      When both *mapping* and *kws* are given and there are
      duplicates, the placeholders from *kws* take precedence.

   safe_substitute(mapping[, **kws])

      Like "substitute()", except that if placeholders are missing
      from *mapping* and *kws*, instead of raising a "KeyError"
      exception, the original placeholder will appear in the resulting
      string intact.  Also, unlike with "substitute()", any other
      appearances of the "$" will simply return "$" instead of raising
      "ValueError".

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

   "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()" を呼び出すので、正規表現を表すような文字列にしては *な
  りません* 。

* *idpattern* – 波括弧でくくらない形式のプレースホルダの表記パターン
  を 示す正規表現です (波括弧は自動的に適切な場所に追加されます)。デフ
  ォ ルトの値は "[_a-z][_a-z0-9]*" という正規表現です。

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

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

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

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

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


String functions
================

The following functions are available to operate on string and Unicode
objects. They are not available as string methods.

string.capwords(s[, sep])

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

string.maketrans(from, to)

   Return a translation table suitable for passing to "translate()",
   that will map each character in *from* into the character at the
   same position in *to*; *from* and *to* must have the same length.

   注釈: Don’t use strings derived from "lowercase" and "uppercase"
     as arguments; in some locales, these don’t have the same length.
     For case conversions, always use "str.lower()" and "str.upper()".


Deprecated string functions
===========================

The following list of functions are also defined as methods of string
and Unicode objects; see section 文字列メソッド for more information
on those.  You should consider these functions as deprecated, although
they will not be removed until Python 3.  The functions defined in
this module are:

string.atof(s)

   バージョン 2.0 で撤廃: Use the "float()" built-in function.

   Convert a string to a floating point number.  The string must have
   the standard syntax for a floating point literal in Python,
   optionally preceded by a sign ("+" or "-").  Note that this behaves
   identical to the built-in function "float()" when passed a string.

   注釈: When passing in a string, values for NaN and Infinity may
     be returned, depending on the underlying C library.  The specific
     set of strings accepted which cause these values to be returned
     depends entirely on the C library and is known to vary.

string.atoi(s[, base])

   バージョン 2.0 で撤廃: Use the "int()" built-in function.

   Convert string *s* to an integer in the given *base*.  The string
   must consist of one or more digits, optionally preceded by a sign
   ("+" or "-").  The *base* defaults to 10.  If it is 0, a default
   base is chosen depending on the leading characters of the string
   (after stripping the sign): "0x" or "0X" means 16, "0" means 8,
   anything else means 10.  If *base* is 16, a leading "0x" or "0X" is
   always accepted, though not required.  This behaves identically to
   the built-in function "int()" when passed a string.  (Also note:
   for a more flexible interpretation of numeric literals, use the
   built-in function "eval()".)

string.atol(s[, base])

   バージョン 2.0 で撤廃: Use the "long()" built-in function.

   Convert string *s* to a long integer in the given *base*. The
   string must consist of one or more digits, optionally preceded by a
   sign ("+" or "-"). The *base* argument has the same meaning as for
   "atoi()".  A trailing "l" or "L" is not allowed, except if the base
   is 0.  Note that when invoked without *base* or with *base* set to
   10, this behaves identical to the built-in function "long()" when
   passed a string.

string.capitalize(word)

   Return a copy of *word* with only its first character capitalized.

string.expandtabs(s[, tabsize])

   Expand tabs in a string replacing them by one or more spaces,
   depending on the current column and the given tab size.  The column
   number is reset to zero after each newline occurring in the string.
   This doesn’t understand other non-printing characters or escape
   sequences.  The tab size defaults to 8.

string.find(s, sub[, start[, end]])

   Return the lowest index in *s* where the substring *sub* is found
   such that *sub* is wholly contained in "s[start:end]".  Return "-1"
   on failure. Defaults for *start* and *end* and interpretation of
   negative values is the same as for slices.

string.rfind(s, sub[, start[, end]])

   Like "find()" but find the highest index.

string.index(s, sub[, start[, end]])

   Like "find()" but raise "ValueError" when the substring is not
   found.

string.rindex(s, sub[, start[, end]])

   Like "rfind()" but raise "ValueError" when the substring is not
   found.

string.count(s, sub[, start[, end]])

   Return the number of (non-overlapping) occurrences of substring
   *sub* in string "s[start:end]". Defaults for *start* and *end* and
   interpretation of negative values are the same as for slices.

string.lower(s)

   Return a copy of *s*, but with upper case letters converted to
   lower case.

string.split(s[, sep[, maxsplit]])

   Return a list of the words of the string *s*.  If the optional
   second argument *sep* is absent or "None", the words are separated
   by arbitrary strings of whitespace characters (space, tab, newline,
   return, formfeed).  If the second argument *sep* is present and not
   "None", it specifies a string to be used as the  word separator.
   The returned list will then have one more item than the number of
   non-overlapping occurrences of the separator in the string. If
   *maxsplit* is given, at most *maxsplit* number of splits occur, and
   the remainder of the string is returned as the final element of the
   list (thus, the list will have at most "maxsplit+1" elements).  If
   *maxsplit* is not specified or "-1", then there is no limit on the
   number of splits (all possible splits are made).

   The behavior of split on an empty string depends on the value of
   *sep*. If *sep* is not specified, or specified as "None", the
   result will be an empty list. If *sep* is specified as any string,
   the result will be a list containing one element which is an empty
   string.

string.rsplit(s[, sep[, maxsplit]])

   Return a list of the words of the string *s*, scanning *s* from the
   end.  To all intents and purposes, the resulting list of words is
   the same as returned by "split()", except when the optional third
   argument *maxsplit* is explicitly specified and nonzero.  If
   *maxsplit* is given, at most *maxsplit* number of splits – the
   *rightmost* ones – occur, and the remainder of the string is
   returned as the first element of the list (thus, the list will have
   at most "maxsplit+1" elements).

   バージョン 2.4 で追加.

string.splitfields(s[, sep[, maxsplit]])

   This function behaves identically to "split()".  (In the past,
   "split()" was only used with one argument, while "splitfields()"
   was only used with two arguments.)

string.join(words[, sep])

   Concatenate a list or tuple of words with intervening occurrences
   of  *sep*. The default value for *sep* is a single space character.
   It is always true that "string.join(string.split(s, sep), sep)"
   equals *s*.

string.joinfields(words[, sep])

   This function behaves identically to "join()".  (In the past,
   "join()" was only used with one argument, while "joinfields()" was
   only used with two arguments.) Note that there is no "joinfields()"
   method on string objects; use the "join()" method instead.

string.lstrip(s[, chars])

   Return a copy of the string with leading characters removed.  If
   *chars* is omitted or "None", whitespace characters are removed.
   If given and not "None", *chars* must be a string; the characters
   in the string will be stripped from the beginning of the string
   this method is called on.

   バージョン 2.2.3 で変更: The *chars* parameter was added.  The
   *chars* parameter cannot be passed in earlier 2.2 versions.

string.rstrip(s[, chars])

   Return a copy of the string with trailing characters removed.  If
   *chars* is omitted or "None", whitespace characters are removed.
   If given and not "None", *chars* must be a string; the characters
   in the string will be stripped from the end of the string this
   method is called on.

   バージョン 2.2.3 で変更: The *chars* parameter was added.  The
   *chars* parameter cannot be passed in earlier 2.2 versions.

string.strip(s[, chars])

   Return a copy of the string with leading and trailing characters
   removed.  If *chars* is omitted or "None", whitespace characters
   are removed.  If given and not "None", *chars* must be a string;
   the characters in the string will be stripped from the both ends of
   the string this method is called on.

   バージョン 2.2.3 で変更: The *chars* parameter was added.  The
   *chars* parameter cannot be passed in earlier 2.2 versions.

string.swapcase(s)

   Return a copy of *s*, but with lower case letters converted to
   upper case and vice versa.

string.translate(s, table[, deletechars])

   Delete all characters from *s* that are in *deletechars* (if
   present), and then translate the characters using *table*, which
   must be a 256-character string giving the translation for each
   character value, indexed by its ordinal.  If *table* is "None",
   then only the character deletion step is performed.

string.upper(s)

   Return a copy of *s*, but with lower case letters converted to
   upper case.

string.ljust(s, width[, fillchar])
string.rjust(s, width[, fillchar])
string.center(s, width[, fillchar])

   These functions respectively left-justify, right-justify and center
   a string in a field of given width.  They return a string that is
   at least *width* characters wide, created by padding the string *s*
   with the character *fillchar* (default is a space) until the given
   width on the right, left or both sides. The string is never
   truncated.

string.zfill(s, width)

   Pad a numeric string *s* on the left with zero digits until the
   given *width* is reached.  Strings starting with a sign are handled
   correctly.

string.replace(s, old, new[, maxreplace])

   Return a copy of string *s* with all occurrences of substring *old*
   replaced by *new*.  If the optional argument *maxreplace* is given,
   the first *maxreplace* occurrences are replaced.
