~ubuntu-branches/ubuntu/trusty/python3.4/trusty-proposed

« back to all changes in this revision

Viewing changes to Doc/library/string.rst

  • Committer: Package Import Robot
  • Author(s): Matthias Klose
  • Date: 2013-11-25 09:44:27 UTC
  • Revision ID: package-import@ubuntu.com-20131125094427-lzxj8ap5w01lmo7f
Tags: upstream-3.4~b1
ImportĀ upstreamĀ versionĀ 3.4~b1

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
:mod:`string` --- Common string operations
 
2
==========================================
 
3
 
 
4
.. module:: string
 
5
   :synopsis: Common string operations.
 
6
 
 
7
**Source code:** :source:`Lib/string.py`
 
8
 
 
9
--------------
 
10
 
 
11
.. seealso::
 
12
 
 
13
   :ref:`textseq`
 
14
 
 
15
   :ref:`string-methods`
 
16
 
 
17
String constants
 
18
----------------
 
19
 
 
20
The constants defined in this module are:
 
21
 
 
22
 
 
23
.. data:: ascii_letters
 
24
 
 
25
   The concatenation of the :const:`ascii_lowercase` and :const:`ascii_uppercase`
 
26
   constants described below.  This value is not locale-dependent.
 
27
 
 
28
 
 
29
.. data:: ascii_lowercase
 
30
 
 
31
   The lowercase letters ``'abcdefghijklmnopqrstuvwxyz'``.  This value is not
 
32
   locale-dependent and will not change.
 
33
 
 
34
 
 
35
.. data:: ascii_uppercase
 
36
 
 
37
   The uppercase letters ``'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``.  This value is not
 
38
   locale-dependent and will not change.
 
39
 
 
40
 
 
41
.. data:: digits
 
42
 
 
43
   The string ``'0123456789'``.
 
44
 
 
45
 
 
46
.. data:: hexdigits
 
47
 
 
48
   The string ``'0123456789abcdefABCDEF'``.
 
49
 
 
50
 
 
51
.. data:: octdigits
 
52
 
 
53
   The string ``'01234567'``.
 
54
 
 
55
 
 
56
.. data:: punctuation
 
57
 
 
58
   String of ASCII characters which are considered punctuation characters
 
59
   in the ``C`` locale.
 
60
 
 
61
 
 
62
.. data:: printable
 
63
 
 
64
   String of ASCII characters which are considered printable.  This is a
 
65
   combination of :const:`digits`, :const:`ascii_letters`, :const:`punctuation`,
 
66
   and :const:`whitespace`.
 
67
 
 
68
 
 
69
.. data:: whitespace
 
70
 
 
71
   A string containing all ASCII characters that are considered whitespace.
 
72
   This includes the characters space, tab, linefeed, return, formfeed, and
 
73
   vertical tab.
 
74
 
 
75
 
 
76
.. _string-formatting:
 
77
 
 
78
String Formatting
 
79
-----------------
 
80
 
 
81
The built-in string class provides the ability to do complex variable
 
82
substitutions and value formatting via the :func:`format` method described in
 
83
:pep:`3101`.  The :class:`Formatter` class in the :mod:`string` module allows
 
84
you to create and customize your own string formatting behaviors using the same
 
85
implementation as the built-in :meth:`format` method.
 
86
 
 
87
 
 
88
.. class:: Formatter
 
89
 
 
90
   The :class:`Formatter` class has the following public methods:
 
91
 
 
92
   .. method:: format(format_string, *args, **kwargs)
 
93
 
 
94
      :meth:`format` is the primary API method.  It takes a format string and
 
95
      an arbitrary set of positional and keyword arguments.
 
96
      :meth:`format` is just a wrapper that calls :meth:`vformat`.
 
97
 
 
98
   .. method:: vformat(format_string, args, kwargs)
 
99
 
 
100
      This function does the actual work of formatting.  It is exposed as a
 
101
      separate function for cases where you want to pass in a predefined
 
102
      dictionary of arguments, rather than unpacking and repacking the
 
103
      dictionary as individual arguments using the ``*args`` and ``**kwargs``
 
104
      syntax.  :meth:`vformat` does the work of breaking up the format string
 
105
      into character data and replacement fields.  It calls the various
 
106
      methods described below.
 
107
 
 
108
   In addition, the :class:`Formatter` defines a number of methods that are
 
109
   intended to be replaced by subclasses:
 
110
 
 
111
   .. method:: parse(format_string)
 
112
 
 
113
      Loop over the format_string and return an iterable of tuples
 
114
      (*literal_text*, *field_name*, *format_spec*, *conversion*).  This is used
 
115
      by :meth:`vformat` to break the string into either literal text, or
 
116
      replacement fields.
 
117
 
 
118
      The values in the tuple conceptually represent a span of literal text
 
119
      followed by a single replacement field.  If there is no literal text
 
120
      (which can happen if two replacement fields occur consecutively), then
 
121
      *literal_text* will be a zero-length string.  If there is no replacement
 
122
      field, then the values of *field_name*, *format_spec* and *conversion*
 
123
      will be ``None``.
 
124
 
 
125
   .. method:: get_field(field_name, args, kwargs)
 
126
 
 
127
      Given *field_name* as returned by :meth:`parse` (see above), convert it to
 
128
      an object to be formatted.  Returns a tuple (obj, used_key).  The default
 
129
      version takes strings of the form defined in :pep:`3101`, such as
 
130
      "0[name]" or "label.title".  *args* and *kwargs* are as passed in to
 
131
      :meth:`vformat`.  The return value *used_key* has the same meaning as the
 
132
      *key* parameter to :meth:`get_value`.
 
133
 
 
134
   .. method:: get_value(key, args, kwargs)
 
135
 
 
136
      Retrieve a given field value.  The *key* argument will be either an
 
137
      integer or a string.  If it is an integer, it represents the index of the
 
138
      positional argument in *args*; if it is a string, then it represents a
 
139
      named argument in *kwargs*.
 
140
 
 
141
      The *args* parameter is set to the list of positional arguments to
 
142
      :meth:`vformat`, and the *kwargs* parameter is set to the dictionary of
 
143
      keyword arguments.
 
144
 
 
145
      For compound field names, these functions are only called for the first
 
146
      component of the field name; Subsequent components are handled through
 
147
      normal attribute and indexing operations.
 
148
 
 
149
      So for example, the field expression '0.name' would cause
 
150
      :meth:`get_value` to be called with a *key* argument of 0.  The ``name``
 
151
      attribute will be looked up after :meth:`get_value` returns by calling the
 
152
      built-in :func:`getattr` function.
 
153
 
 
154
      If the index or keyword refers to an item that does not exist, then an
 
155
      :exc:`IndexError` or :exc:`KeyError` should be raised.
 
156
 
 
157
   .. method:: check_unused_args(used_args, args, kwargs)
 
158
 
 
159
      Implement checking for unused arguments if desired.  The arguments to this
 
160
      function is the set of all argument keys that were actually referred to in
 
161
      the format string (integers for positional arguments, and strings for
 
162
      named arguments), and a reference to the *args* and *kwargs* that was
 
163
      passed to vformat.  The set of unused args can be calculated from these
 
164
      parameters.  :meth:`check_unused_args` is assumed to raise an exception if
 
165
      the check fails.
 
166
 
 
167
   .. method:: format_field(value, format_spec)
 
168
 
 
169
      :meth:`format_field` simply calls the global :func:`format` built-in.  The
 
170
      method is provided so that subclasses can override it.
 
171
 
 
172
   .. method:: convert_field(value, conversion)
 
173
 
 
174
      Converts the value (returned by :meth:`get_field`) given a conversion type
 
175
      (as in the tuple returned by the :meth:`parse` method).  The default
 
176
      version understands 's' (str), 'r' (repr) and 'a' (ascii) conversion
 
177
      types.
 
178
 
 
179
 
 
180
.. _formatstrings:
 
181
 
 
182
Format String Syntax
 
183
--------------------
 
184
 
 
185
The :meth:`str.format` method and the :class:`Formatter` class share the same
 
186
syntax for format strings (although in the case of :class:`Formatter`,
 
187
subclasses can define their own format string syntax).
 
188
 
 
189
Format strings contain "replacement fields" surrounded by curly braces ``{}``.
 
190
Anything that is not contained in braces is considered literal text, which is
 
191
copied unchanged to the output.  If you need to include a brace character in the
 
192
literal text, it can be escaped by doubling: ``{{`` and ``}}``.
 
193
 
 
194
The grammar for a replacement field is as follows:
 
195
 
 
196
   .. productionlist:: sf
 
197
      replacement_field: "{" [`field_name`] ["!" `conversion`] [":" `format_spec`] "}"
 
198
      field_name: arg_name ("." `attribute_name` | "[" `element_index` "]")*
 
199
      arg_name: [`identifier` | `integer`]
 
200
      attribute_name: `identifier`
 
201
      element_index: `integer` | `index_string`
 
202
      index_string: <any source character except "]"> +
 
203
      conversion: "r" | "s" | "a"
 
204
      format_spec: <described in the next section>
 
205
 
 
206
In less formal terms, the replacement field can start with a *field_name* that specifies
 
207
the object whose value is to be formatted and inserted
 
208
into the output instead of the replacement field.
 
209
The *field_name* is optionally followed by a  *conversion* field, which is
 
210
preceded by an exclamation point ``'!'``, and a *format_spec*, which is preceded
 
211
by a colon ``':'``.  These specify a non-default format for the replacement value.
 
212
 
 
213
See also the :ref:`formatspec` section.
 
214
 
 
215
The *field_name* itself begins with an *arg_name* that is either a number or a
 
216
keyword.  If it's a number, it refers to a positional argument, and if it's a keyword,
 
217
it refers to a named keyword argument.  If the numerical arg_names in a format string
 
218
are 0, 1, 2, ... in sequence, they can all be omitted (not just some)
 
219
and the numbers 0, 1, 2, ... will be automatically inserted in that order.
 
220
Because *arg_name* is not quote-delimited, it is not possible to specify arbitrary
 
221
dictionary keys (e.g., the strings ``'10'`` or ``':-]'``) within a format string.
 
222
The *arg_name* can be followed by any number of index or
 
223
attribute expressions. An expression of the form ``'.name'`` selects the named
 
224
attribute using :func:`getattr`, while an expression of the form ``'[index]'``
 
225
does an index lookup using :func:`__getitem__`.
 
226
 
 
227
.. versionchanged:: 3.1
 
228
   The positional argument specifiers can be omitted, so ``'{} {}'`` is
 
229
   equivalent to ``'{0} {1}'``.
 
230
 
 
231
Some simple format string examples::
 
232
 
 
233
   "First, thou shalt count to {0}" # References first positional argument
 
234
   "Bring me a {}"                  # Implicitly references the first positional argument
 
235
   "From {} to {}"                  # Same as "From {0} to {1}"
 
236
   "My quest is {name}"             # References keyword argument 'name'
 
237
   "Weight in tons {0.weight}"      # 'weight' attribute of first positional arg
 
238
   "Units destroyed: {players[0]}"  # First element of keyword argument 'players'.
 
239
 
 
240
The *conversion* field causes a type coercion before formatting.  Normally, the
 
241
job of formatting a value is done by the :meth:`__format__` method of the value
 
242
itself.  However, in some cases it is desirable to force a type to be formatted
 
243
as a string, overriding its own definition of formatting.  By converting the
 
244
value to a string before calling :meth:`__format__`, the normal formatting logic
 
245
is bypassed.
 
246
 
 
247
Three conversion flags are currently supported: ``'!s'`` which calls :func:`str`
 
248
on the value, ``'!r'`` which calls :func:`repr` and ``'!a'`` which calls
 
249
:func:`ascii`.
 
250
 
 
251
Some examples::
 
252
 
 
253
   "Harold's a clever {0!s}"        # Calls str() on the argument first
 
254
   "Bring out the holy {name!r}"    # Calls repr() on the argument first
 
255
   "More {!a}"                      # Calls ascii() on the argument first
 
256
 
 
257
The *format_spec* field contains a specification of how the value should be
 
258
presented, including such details as field width, alignment, padding, decimal
 
259
precision and so on.  Each value type can define its own "formatting
 
260
mini-language" or interpretation of the *format_spec*.
 
261
 
 
262
Most built-in types support a common formatting mini-language, which is
 
263
described in the next section.
 
264
 
 
265
A *format_spec* field can also include nested replacement fields within it.
 
266
These nested replacement fields can contain only a field name; conversion flags
 
267
and format specifications are not allowed.  The replacement fields within the
 
268
format_spec are substituted before the *format_spec* string is interpreted.
 
269
This allows the formatting of a value to be dynamically specified.
 
270
 
 
271
See the :ref:`formatexamples` section for some examples.
 
272
 
 
273
 
 
274
.. _formatspec:
 
275
 
 
276
Format Specification Mini-Language
 
277
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
278
 
 
279
"Format specifications" are used within replacement fields contained within a
 
280
format string to define how individual values are presented (see
 
281
:ref:`formatstrings`).  They can also be passed directly to the built-in
 
282
:func:`format` function.  Each formattable type may define how the format
 
283
specification is to be interpreted.
 
284
 
 
285
Most built-in types implement the following options for format specifications,
 
286
although some of the formatting options are only supported by the numeric types.
 
287
 
 
288
A general convention is that an empty format string (``""``) produces
 
289
the same result as if you had called :func:`str` on the value. A
 
290
non-empty format string typically modifies the result.
 
291
 
 
292
The general form of a *standard format specifier* is:
 
293
 
 
294
.. productionlist:: sf
 
295
   format_spec: [[`fill`]`align`][`sign`][#][0][`width`][,][.`precision`][`type`]
 
296
   fill: <any character>
 
297
   align: "<" | ">" | "=" | "^"
 
298
   sign: "+" | "-" | " "
 
299
   width: `integer`
 
300
   precision: `integer`
 
301
   type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
 
302
 
 
303
If a valid *align* value is specified, it can be preceded by a *fill*
 
304
character that can be any character and defaults to a space if omitted.
 
305
Note that it is not possible to use ``{`` and ``}`` as *fill* char while
 
306
using the :meth:`str.format` method; this limitation however doesn't
 
307
affect the :func:`format` function.
 
308
 
 
309
The meaning of the various alignment options is as follows:
 
310
 
 
311
   +---------+----------------------------------------------------------+
 
312
   | Option  | Meaning                                                  |
 
313
   +=========+==========================================================+
 
314
   | ``'<'`` | Forces the field to be left-aligned within the available |
 
315
   |         | space (this is the default for most objects).            |
 
316
   +---------+----------------------------------------------------------+
 
317
   | ``'>'`` | Forces the field to be right-aligned within the          |
 
318
   |         | available space (this is the default for numbers).       |
 
319
   +---------+----------------------------------------------------------+
 
320
   | ``'='`` | Forces the padding to be placed after the sign (if any)  |
 
321
   |         | but before the digits.  This is used for printing fields |
 
322
   |         | in the form '+000000120'. This alignment option is only  |
 
323
   |         | valid for numeric types.                                 |
 
324
   +---------+----------------------------------------------------------+
 
325
   | ``'^'`` | Forces the field to be centered within the available     |
 
326
   |         | space.                                                   |
 
327
   +---------+----------------------------------------------------------+
 
328
 
 
329
Note that unless a minimum field width is defined, the field width will always
 
330
be the same size as the data to fill it, so that the alignment option has no
 
331
meaning in this case.
 
332
 
 
333
The *sign* option is only valid for number types, and can be one of the
 
334
following:
 
335
 
 
336
   +---------+----------------------------------------------------------+
 
337
   | Option  | Meaning                                                  |
 
338
   +=========+==========================================================+
 
339
   | ``'+'`` | indicates that a sign should be used for both            |
 
340
   |         | positive as well as negative numbers.                    |
 
341
   +---------+----------------------------------------------------------+
 
342
   | ``'-'`` | indicates that a sign should be used only for negative   |
 
343
   |         | numbers (this is the default behavior).                  |
 
344
   +---------+----------------------------------------------------------+
 
345
   | space   | indicates that a leading space should be used on         |
 
346
   |         | positive numbers, and a minus sign on negative numbers.  |
 
347
   +---------+----------------------------------------------------------+
 
348
 
 
349
 
 
350
The ``'#'`` option causes the "alternate form" to be used for the
 
351
conversion.  The alternate form is defined differently for different
 
352
types.  This option is only valid for integer, float, complex and
 
353
Decimal types. For integers, when binary, octal, or hexadecimal output
 
354
is used, this option adds the prefix respective ``'0b'``, ``'0o'``, or
 
355
``'0x'`` to the output value. For floats, complex and Decimal the
 
356
alternate form causes the result of the conversion to always contain a
 
357
decimal-point character, even if no digits follow it. Normally, a
 
358
decimal-point character appears in the result of these conversions
 
359
only if a digit follows it. In addition, for ``'g'`` and ``'G'``
 
360
conversions, trailing zeros are not removed from the result.
 
361
 
 
362
The ``','`` option signals the use of a comma for a thousands separator.
 
363
For a locale aware separator, use the ``'n'`` integer presentation type
 
364
instead.
 
365
 
 
366
.. versionchanged:: 3.1
 
367
   Added the ``','`` option (see also :pep:`378`).
 
368
 
 
369
*width* is a decimal integer defining the minimum field width.  If not
 
370
specified, then the field width will be determined by the content.
 
371
 
 
372
Preceding the *width* field by a zero (``'0'``) character enables
 
373
sign-aware zero-padding for numeric types.  This is equivalent to a *fill*
 
374
character of ``'0'`` with an *alignment* type of ``'='``.
 
375
 
 
376
The *precision* is a decimal number indicating how many digits should be
 
377
displayed after the decimal point for a floating point value formatted with
 
378
``'f'`` and ``'F'``, or before and after the decimal point for a floating point
 
379
value formatted with ``'g'`` or ``'G'``.  For non-number types the field
 
380
indicates the maximum field size - in other words, how many characters will be
 
381
used from the field content. The *precision* is not allowed for integer values.
 
382
 
 
383
Finally, the *type* determines how the data should be presented.
 
384
 
 
385
The available string presentation types are:
 
386
 
 
387
   +---------+----------------------------------------------------------+
 
388
   | Type    | Meaning                                                  |
 
389
   +=========+==========================================================+
 
390
   | ``'s'`` | String format. This is the default type for strings and  |
 
391
   |         | may be omitted.                                          |
 
392
   +---------+----------------------------------------------------------+
 
393
   | None    | The same as ``'s'``.                                     |
 
394
   +---------+----------------------------------------------------------+
 
395
 
 
396
The available integer presentation types are:
 
397
 
 
398
   +---------+----------------------------------------------------------+
 
399
   | Type    | Meaning                                                  |
 
400
   +=========+==========================================================+
 
401
   | ``'b'`` | Binary format. Outputs the number in base 2.             |
 
402
   +---------+----------------------------------------------------------+
 
403
   | ``'c'`` | Character. Converts the integer to the corresponding     |
 
404
   |         | unicode character before printing.                       |
 
405
   +---------+----------------------------------------------------------+
 
406
   | ``'d'`` | Decimal Integer. Outputs the number in base 10.          |
 
407
   +---------+----------------------------------------------------------+
 
408
   | ``'o'`` | Octal format. Outputs the number in base 8.              |
 
409
   +---------+----------------------------------------------------------+
 
410
   | ``'x'`` | Hex format. Outputs the number in base 16, using lower-  |
 
411
   |         | case letters for the digits above 9.                     |
 
412
   +---------+----------------------------------------------------------+
 
413
   | ``'X'`` | Hex format. Outputs the number in base 16, using upper-  |
 
414
   |         | case letters for the digits above 9.                     |
 
415
   +---------+----------------------------------------------------------+
 
416
   | ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
 
417
   |         | the current locale setting to insert the appropriate     |
 
418
   |         | number separator characters.                             |
 
419
   +---------+----------------------------------------------------------+
 
420
   | None    | The same as ``'d'``.                                     |
 
421
   +---------+----------------------------------------------------------+
 
422
 
 
423
In addition to the above presentation types, integers can be formatted
 
424
with the floating point presentation types listed below (except
 
425
``'n'`` and None). When doing so, :func:`float` is used to convert the
 
426
integer to a floating point number before formatting.
 
427
 
 
428
The available presentation types for floating point and decimal values are:
 
429
 
 
430
   +---------+----------------------------------------------------------+
 
431
   | Type    | Meaning                                                  |
 
432
   +=========+==========================================================+
 
433
   | ``'e'`` | Exponent notation. Prints the number in scientific       |
 
434
   |         | notation using the letter 'e' to indicate the exponent.  |
 
435
   |         | The default precision is ``6``.                          |
 
436
   +---------+----------------------------------------------------------+
 
437
   | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an     |
 
438
   |         | upper case 'E' as the separator character.               |
 
439
   +---------+----------------------------------------------------------+
 
440
   | ``'f'`` | Fixed point. Displays the number as a fixed-point        |
 
441
   |         | number.  The default precision is ``6``.                 |
 
442
   +---------+----------------------------------------------------------+
 
443
   | ``'F'`` | Fixed point. Same as ``'f'``, but converts ``nan`` to    |
 
444
   |         | ``NAN`` and ``inf`` to ``INF``.                          |
 
445
   +---------+----------------------------------------------------------+
 
446
   | ``'g'`` | General format.  For a given precision ``p >= 1``,       |
 
447
   |         | this rounds the number to ``p`` significant digits and   |
 
448
   |         | then formats the result in either fixed-point format     |
 
449
   |         | or in scientific notation, depending on its magnitude.   |
 
450
   |         |                                                          |
 
451
   |         | The precise rules are as follows: suppose that the       |
 
452
   |         | result formatted with presentation type ``'e'`` and      |
 
453
   |         | precision ``p-1`` would have exponent ``exp``.  Then     |
 
454
   |         | if ``-4 <= exp < p``, the number is formatted            |
 
455
   |         | with presentation type ``'f'`` and precision             |
 
456
   |         | ``p-1-exp``.  Otherwise, the number is formatted         |
 
457
   |         | with presentation type ``'e'`` and precision ``p-1``.    |
 
458
   |         | In both cases insignificant trailing zeros are removed   |
 
459
   |         | from the significand, and the decimal point is also      |
 
460
   |         | removed if there are no remaining digits following it.   |
 
461
   |         |                                                          |
 
462
   |         | Positive and negative infinity, positive and negative    |
 
463
   |         | zero, and nans, are formatted as ``inf``, ``-inf``,      |
 
464
   |         | ``0``, ``-0`` and ``nan`` respectively, regardless of    |
 
465
   |         | the precision.                                           |
 
466
   |         |                                                          |
 
467
   |         | A precision of ``0`` is treated as equivalent to a       |
 
468
   |         | precision of ``1``.  The default precision is ``6``.     |
 
469
   +---------+----------------------------------------------------------+
 
470
   | ``'G'`` | General format. Same as ``'g'`` except switches to       |
 
471
   |         | ``'E'`` if the number gets too large. The                |
 
472
   |         | representations of infinity and NaN are uppercased, too. |
 
473
   +---------+----------------------------------------------------------+
 
474
   | ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
 
475
   |         | the current locale setting to insert the appropriate     |
 
476
   |         | number separator characters.                             |
 
477
   +---------+----------------------------------------------------------+
 
478
   | ``'%'`` | Percentage. Multiplies the number by 100 and displays    |
 
479
   |         | in fixed (``'f'``) format, followed by a percent sign.   |
 
480
   +---------+----------------------------------------------------------+
 
481
   | None    | Similar to ``'g'``, except with at least one digit past  |
 
482
   |         | the decimal point and a default precision of 12. This is |
 
483
   |         | intended to match :func:`str`, except you can add the    |
 
484
   |         | other format modifiers.                                  |
 
485
   +---------+----------------------------------------------------------+
 
486
 
 
487
 
 
488
.. _formatexamples:
 
489
 
 
490
Format examples
 
491
^^^^^^^^^^^^^^^
 
492
 
 
493
This section contains examples of the new format syntax and comparison with
 
494
the old ``%``-formatting.
 
495
 
 
496
In most of the cases the syntax is similar to the old ``%``-formatting, with the
 
497
addition of the ``{}`` and with ``:`` used instead of ``%``.
 
498
For example, ``'%03.2f'`` can be translated to ``'{:03.2f}'``.
 
499
 
 
500
The new format syntax also supports new and different options, shown in the
 
501
follow examples.
 
502
 
 
503
Accessing arguments by position::
 
504
 
 
505
   >>> '{0}, {1}, {2}'.format('a', 'b', 'c')
 
506
   'a, b, c'
 
507
   >>> '{}, {}, {}'.format('a', 'b', 'c')  # 3.1+ only
 
508
   'a, b, c'
 
509
   >>> '{2}, {1}, {0}'.format('a', 'b', 'c')
 
510
   'c, b, a'
 
511
   >>> '{2}, {1}, {0}'.format(*'abc')      # unpacking argument sequence
 
512
   'c, b, a'
 
513
   >>> '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated
 
514
   'abracadabra'
 
515
 
 
516
Accessing arguments by name::
 
517
 
 
518
   >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
 
519
   'Coordinates: 37.24N, -115.81W'
 
520
   >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
 
521
   >>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
 
522
   'Coordinates: 37.24N, -115.81W'
 
523
 
 
524
Accessing arguments' attributes::
 
525
 
 
526
   >>> c = 3-5j
 
527
   >>> ('The complex number {0} is formed from the real part {0.real} '
 
528
   ...  'and the imaginary part {0.imag}.').format(c)
 
529
   'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
 
530
   >>> class Point:
 
531
   ...     def __init__(self, x, y):
 
532
   ...         self.x, self.y = x, y
 
533
   ...     def __str__(self):
 
534
   ...         return 'Point({self.x}, {self.y})'.format(self=self)
 
535
   ...
 
536
   >>> str(Point(4, 2))
 
537
   'Point(4, 2)'
 
538
 
 
539
Accessing arguments' items::
 
540
 
 
541
   >>> coord = (3, 5)
 
542
   >>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
 
543
   'X: 3;  Y: 5'
 
544
 
 
545
Replacing ``%s`` and ``%r``::
 
546
 
 
547
   >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
 
548
   "repr() shows quotes: 'test1'; str() doesn't: test2"
 
549
 
 
550
Aligning the text and specifying a width::
 
551
 
 
552
   >>> '{:<30}'.format('left aligned')
 
553
   'left aligned                  '
 
554
   >>> '{:>30}'.format('right aligned')
 
555
   '                 right aligned'
 
556
   >>> '{:^30}'.format('centered')
 
557
   '           centered           '
 
558
   >>> '{:*^30}'.format('centered')  # use '*' as a fill char
 
559
   '***********centered***********'
 
560
 
 
561
Replacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign::
 
562
 
 
563
   >>> '{:+f}; {:+f}'.format(3.14, -3.14)  # show it always
 
564
   '+3.140000; -3.140000'
 
565
   >>> '{: f}; {: f}'.format(3.14, -3.14)  # show a space for positive numbers
 
566
   ' 3.140000; -3.140000'
 
567
   >>> '{:-f}; {:-f}'.format(3.14, -3.14)  # show only the minus -- same as '{:f}; {:f}'
 
568
   '3.140000; -3.140000'
 
569
 
 
570
Replacing ``%x`` and ``%o`` and converting the value to different bases::
 
571
 
 
572
   >>> # format also supports binary numbers
 
573
   >>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
 
574
   'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
 
575
   >>> # with 0x, 0o, or 0b as prefix:
 
576
   >>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
 
577
   'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'
 
578
 
 
579
Using the comma as a thousands separator::
 
580
 
 
581
   >>> '{:,}'.format(1234567890)
 
582
   '1,234,567,890'
 
583
 
 
584
Expressing a percentage::
 
585
 
 
586
   >>> points = 19
 
587
   >>> total = 22
 
588
   >>> 'Correct answers: {:.2%}'.format(points/total)
 
589
   'Correct answers: 86.36%'
 
590
 
 
591
Using type-specific formatting::
 
592
 
 
593
   >>> import datetime
 
594
   >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
 
595
   >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
 
596
   '2010-07-04 12:15:58'
 
597
 
 
598
Nesting arguments and more complex examples::
 
599
 
 
600
   >>> for align, text in zip('<^>', ['left', 'center', 'right']):
 
601
   ...     '{0:{fill}{align}16}'.format(text, fill=align, align=align)
 
602
   ...
 
603
   'left<<<<<<<<<<<<'
 
604
   '^^^^^center^^^^^'
 
605
   '>>>>>>>>>>>right'
 
606
   >>>
 
607
   >>> octets = [192, 168, 0, 1]
 
608
   >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
 
609
   'C0A80001'
 
610
   >>> int(_, 16)
 
611
   3232235521
 
612
   >>>
 
613
   >>> width = 5
 
614
   >>> for num in range(5,12): #doctest: +NORMALIZE_WHITESPACE
 
615
   ...     for base in 'dXob':
 
616
   ...         print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
 
617
   ...     print()
 
618
   ...
 
619
       5     5     5   101
 
620
       6     6     6   110
 
621
       7     7     7   111
 
622
       8     8    10  1000
 
623
       9     9    11  1001
 
624
      10     A    12  1010
 
625
      11     B    13  1011
 
626
 
 
627
 
 
628
 
 
629
.. _template-strings:
 
630
 
 
631
Template strings
 
632
----------------
 
633
 
 
634
Templates provide simpler string substitutions as described in :pep:`292`.
 
635
Instead of the normal ``%``\ -based substitutions, Templates support ``$``\
 
636
-based substitutions, using the following rules:
 
637
 
 
638
* ``$$`` is an escape; it is replaced with a single ``$``.
 
639
 
 
640
* ``$identifier`` names a substitution placeholder matching a mapping key of
 
641
  ``"identifier"``.  By default, ``"identifier"`` must spell a Python
 
642
  identifier.  The first non-identifier character after the ``$`` character
 
643
  terminates this placeholder specification.
 
644
 
 
645
* ``${identifier}`` is equivalent to ``$identifier``.  It is required when valid
 
646
  identifier characters follow the placeholder but are not part of the
 
647
  placeholder, such as ``"${noun}ification"``.
 
648
 
 
649
Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
 
650
being raised.
 
651
 
 
652
The :mod:`string` module provides a :class:`Template` class that implements
 
653
these rules.  The methods of :class:`Template` are:
 
654
 
 
655
 
 
656
.. class:: Template(template)
 
657
 
 
658
   The constructor takes a single argument which is the template string.
 
659
 
 
660
 
 
661
   .. method:: substitute(mapping, **kwds)
 
662
 
 
663
      Performs the template substitution, returning a new string.  *mapping* is
 
664
      any dictionary-like object with keys that match the placeholders in the
 
665
      template.  Alternatively, you can provide keyword arguments, where the
 
666
      keywords are the placeholders.  When both *mapping* and *kwds* are given
 
667
      and there are duplicates, the placeholders from *kwds* take precedence.
 
668
 
 
669
 
 
670
   .. method:: safe_substitute(mapping, **kwds)
 
671
 
 
672
      Like :meth:`substitute`, except that if placeholders are missing from
 
673
      *mapping* and *kwds*, instead of raising a :exc:`KeyError` exception, the
 
674
      original placeholder will appear in the resulting string intact.  Also,
 
675
      unlike with :meth:`substitute`, any other appearances of the ``$`` will
 
676
      simply return ``$`` instead of raising :exc:`ValueError`.
 
677
 
 
678
      While other exceptions may still occur, this method is called "safe"
 
679
      because substitutions always tries to return a usable string instead of
 
680
      raising an exception.  In another sense, :meth:`safe_substitute` may be
 
681
      anything other than safe, since it will silently ignore malformed
 
682
      templates containing dangling delimiters, unmatched braces, or
 
683
      placeholders that are not valid Python identifiers.
 
684
 
 
685
   :class:`Template` instances also provide one public data attribute:
 
686
 
 
687
   .. attribute:: template
 
688
 
 
689
      This is the object passed to the constructor's *template* argument.  In
 
690
      general, you shouldn't change it, but read-only access is not enforced.
 
691
 
 
692
Here is an example of how to use a Template::
 
693
 
 
694
   >>> from string import Template
 
695
   >>> s = Template('$who likes $what')
 
696
   >>> s.substitute(who='tim', what='kung pao')
 
697
   'tim likes kung pao'
 
698
   >>> d = dict(who='tim')
 
699
   >>> Template('Give $who $100').substitute(d)
 
700
   Traceback (most recent call last):
 
701
   ...
 
702
   ValueError: Invalid placeholder in string: line 1, col 11
 
703
   >>> Template('$who likes $what').substitute(d)
 
704
   Traceback (most recent call last):
 
705
   ...
 
706
   KeyError: 'what'
 
707
   >>> Template('$who likes $what').safe_substitute(d)
 
708
   'tim likes $what'
 
709
 
 
710
Advanced usage: you can derive subclasses of :class:`Template` to customize the
 
711
placeholder syntax, delimiter character, or the entire regular expression used
 
712
to parse template strings.  To do this, you can override these class attributes:
 
713
 
 
714
* *delimiter* -- This is the literal string describing a placeholder introducing
 
715
  delimiter.  The default value is ``$``.  Note that this should *not* be a
 
716
  regular expression, as the implementation will call :meth:`re.escape` on this
 
717
  string as needed.
 
718
 
 
719
* *idpattern* -- This is the regular expression describing the pattern for
 
720
  non-braced placeholders (the braces will be added automatically as
 
721
  appropriate).  The default value is the regular expression
 
722
  ``[_a-z][_a-z0-9]*``.
 
723
 
 
724
* *flags* -- The regular expression flags that will be applied when compiling
 
725
  the regular expression used for recognizing substitutions.  The default value
 
726
  is ``re.IGNORECASE``.  Note that ``re.VERBOSE`` will always be added to the
 
727
  flags, so custom *idpattern*\ s must follow conventions for verbose regular
 
728
  expressions.
 
729
 
 
730
  .. versionadded:: 3.2
 
731
 
 
732
Alternatively, you can provide the entire regular expression pattern by
 
733
overriding the class attribute *pattern*.  If you do this, the value must be a
 
734
regular expression object with four named capturing groups.  The capturing
 
735
groups correspond to the rules given above, along with the invalid placeholder
 
736
rule:
 
737
 
 
738
* *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the
 
739
  default pattern.
 
740
 
 
741
* *named* -- This group matches the unbraced placeholder name; it should not
 
742
  include the delimiter in capturing group.
 
743
 
 
744
* *braced* -- This group matches the brace enclosed placeholder name; it should
 
745
  not include either the delimiter or braces in the capturing group.
 
746
 
 
747
* *invalid* -- This group matches any other delimiter pattern (usually a single
 
748
  delimiter), and it should appear last in the regular expression.
 
749
 
 
750
 
 
751
Helper functions
 
752
----------------
 
753
 
 
754
.. function:: capwords(s, sep=None)
 
755
 
 
756
   Split the argument into words using :meth:`str.split`, capitalize each word
 
757
   using :meth:`str.capitalize`, and join the capitalized words using
 
758
   :meth:`str.join`.  If the optional second argument *sep* is absent
 
759
   or ``None``, runs of whitespace characters are replaced by a single space
 
760
   and leading and trailing whitespace are removed, otherwise *sep* is used to
 
761
   split and join the words.
 
762