Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | :mod:`string` --- Common string operations |
| 2 | ========================================== |
| 3 | |
| 4 | .. module:: string |
| 5 | :synopsis: Common string operations. |
| 6 | |
| 7 | |
| 8 | .. index:: module: re |
| 9 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 10 | The :mod:`string` module contains a number of useful constants and classes, as |
| 11 | well as some deprecated legacy functions that are also available as methods on |
| 12 | strings. In addition, Python's built-in string classes support the sequence type |
| 13 | methods described in the :ref:`typesseq` section, and also the string-specific |
| 14 | methods described in the :ref:`string-methods` section. To output formatted |
| 15 | strings, see the :ref:`string-formatting` section. Also, see the :mod:`re` |
| 16 | module for string functions based on regular expressions. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 17 | |
| 18 | |
| 19 | String constants |
| 20 | ---------------- |
| 21 | |
| 22 | The constants defined in this module are: |
| 23 | |
| 24 | |
| 25 | .. data:: ascii_letters |
| 26 | |
| 27 | The concatenation of the :const:`ascii_lowercase` and :const:`ascii_uppercase` |
| 28 | constants described below. This value is not locale-dependent. |
| 29 | |
| 30 | |
| 31 | .. data:: ascii_lowercase |
| 32 | |
| 33 | The lowercase letters ``'abcdefghijklmnopqrstuvwxyz'``. This value is not |
| 34 | locale-dependent and will not change. |
| 35 | |
| 36 | |
| 37 | .. data:: ascii_uppercase |
| 38 | |
| 39 | The uppercase letters ``'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. This value is not |
| 40 | locale-dependent and will not change. |
| 41 | |
| 42 | |
| 43 | .. data:: digits |
| 44 | |
| 45 | The string ``'0123456789'``. |
| 46 | |
| 47 | |
| 48 | .. data:: hexdigits |
| 49 | |
| 50 | The string ``'0123456789abcdefABCDEF'``. |
| 51 | |
| 52 | |
| 53 | .. data:: octdigits |
| 54 | |
| 55 | The string ``'01234567'``. |
| 56 | |
| 57 | |
| 58 | .. data:: punctuation |
| 59 | |
| 60 | String of ASCII characters which are considered punctuation characters |
| 61 | in the ``C`` locale. |
| 62 | |
| 63 | |
| 64 | .. data:: printable |
| 65 | |
| 66 | String of ASCII characters which are considered printable. This is a |
| 67 | combination of :const:`digits`, :const:`ascii_letters`, :const:`punctuation`, |
| 68 | and :const:`whitespace`. |
| 69 | |
| 70 | |
| 71 | .. data:: whitespace |
| 72 | |
Georg Brandl | 5076740 | 2008-11-22 08:31:09 +0000 | [diff] [blame] | 73 | A string containing all ASCII characters that are considered whitespace. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 74 | This includes the characters space, tab, linefeed, return, formfeed, and |
| 75 | vertical tab. |
| 76 | |
| 77 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 78 | .. _string-formatting: |
| 79 | |
| 80 | String Formatting |
| 81 | ----------------- |
| 82 | |
Benjamin Peterson | 50923f9 | 2008-05-25 19:45:17 +0000 | [diff] [blame] | 83 | The built-in string class provides the ability to do complex variable |
| 84 | substitutions and value formatting via the :func:`format` method described in |
| 85 | :pep:`3101`. The :class:`Formatter` class in the :mod:`string` module allows |
| 86 | you to create and customize your own string formatting behaviors using the same |
| 87 | implementation as the built-in :meth:`format` method. |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 88 | |
Benjamin Peterson | 1baf465 | 2009-12-31 03:11:23 +0000 | [diff] [blame] | 89 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 90 | .. class:: Formatter |
| 91 | |
| 92 | The :class:`Formatter` class has the following public methods: |
| 93 | |
| 94 | .. method:: format(format_string, *args, *kwargs) |
| 95 | |
| 96 | :meth:`format` is the primary API method. It takes a format template |
| 97 | string, and an arbitrary set of positional and keyword argument. |
| 98 | :meth:`format` is just a wrapper that calls :meth:`vformat`. |
| 99 | |
| 100 | .. method:: vformat(format_string, args, kwargs) |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 101 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 102 | This function does the actual work of formatting. It is exposed as a |
| 103 | separate function for cases where you want to pass in a predefined |
| 104 | dictionary of arguments, rather than unpacking and repacking the |
| 105 | dictionary as individual arguments using the ``*args`` and ``**kwds`` |
| 106 | syntax. :meth:`vformat` does the work of breaking up the format template |
| 107 | string into character data and replacement fields. It calls the various |
| 108 | methods described below. |
| 109 | |
| 110 | In addition, the :class:`Formatter` defines a number of methods that are |
| 111 | intended to be replaced by subclasses: |
| 112 | |
| 113 | .. method:: parse(format_string) |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 114 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 115 | Loop over the format_string and return an iterable of tuples |
| 116 | (*literal_text*, *field_name*, *format_spec*, *conversion*). This is used |
| 117 | by :meth:`vformat` to break the string in to either literal text, or |
| 118 | replacement fields. |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 119 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 120 | The values in the tuple conceptually represent a span of literal text |
| 121 | followed by a single replacement field. If there is no literal text |
| 122 | (which can happen if two replacement fields occur consecutively), then |
| 123 | *literal_text* will be a zero-length string. If there is no replacement |
| 124 | field, then the values of *field_name*, *format_spec* and *conversion* |
| 125 | will be ``None``. |
| 126 | |
Eric Smith | 9d4ba39 | 2007-09-02 15:33:26 +0000 | [diff] [blame] | 127 | .. method:: get_field(field_name, args, kwargs) |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 128 | |
| 129 | Given *field_name* as returned by :meth:`parse` (see above), convert it to |
Georg Brandl | 7f13e6b | 2007-08-31 10:37:15 +0000 | [diff] [blame] | 130 | an object to be formatted. Returns a tuple (obj, used_key). The default |
| 131 | version takes strings of the form defined in :pep:`3101`, such as |
| 132 | "0[name]" or "label.title". *args* and *kwargs* are as passed in to |
| 133 | :meth:`vformat`. The return value *used_key* has the same meaning as the |
| 134 | *key* parameter to :meth:`get_value`. |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 135 | |
| 136 | .. method:: get_value(key, args, kwargs) |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 137 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 138 | Retrieve a given field value. The *key* argument will be either an |
| 139 | integer or a string. If it is an integer, it represents the index of the |
| 140 | positional argument in *args*; if it is a string, then it represents a |
| 141 | named argument in *kwargs*. |
| 142 | |
| 143 | The *args* parameter is set to the list of positional arguments to |
| 144 | :meth:`vformat`, and the *kwargs* parameter is set to the dictionary of |
| 145 | keyword arguments. |
| 146 | |
| 147 | For compound field names, these functions are only called for the first |
| 148 | component of the field name; Subsequent components are handled through |
| 149 | normal attribute and indexing operations. |
| 150 | |
| 151 | So for example, the field expression '0.name' would cause |
| 152 | :meth:`get_value` to be called with a *key* argument of 0. The ``name`` |
| 153 | attribute will be looked up after :meth:`get_value` returns by calling the |
| 154 | built-in :func:`getattr` function. |
| 155 | |
| 156 | If the index or keyword refers to an item that does not exist, then an |
| 157 | :exc:`IndexError` or :exc:`KeyError` should be raised. |
| 158 | |
| 159 | .. method:: check_unused_args(used_args, args, kwargs) |
| 160 | |
| 161 | Implement checking for unused arguments if desired. The arguments to this |
| 162 | function is the set of all argument keys that were actually referred to in |
| 163 | the format string (integers for positional arguments, and strings for |
| 164 | named arguments), and a reference to the *args* and *kwargs* that was |
| 165 | passed to vformat. The set of unused args can be calculated from these |
| 166 | parameters. :meth:`check_unused_args` is assumed to throw an exception if |
| 167 | the check fails. |
| 168 | |
| 169 | .. method:: format_field(value, format_spec) |
| 170 | |
| 171 | :meth:`format_field` simply calls the global :func:`format` built-in. The |
| 172 | method is provided so that subclasses can override it. |
| 173 | |
| 174 | .. method:: convert_field(value, conversion) |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 175 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 176 | Converts the value (returned by :meth:`get_field`) given a conversion type |
| 177 | (as in the tuple returned by the :meth:`parse` method.) The default |
| 178 | version understands 'r' (repr) and 's' (str) conversion types. |
| 179 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 180 | |
| 181 | .. _formatstrings: |
| 182 | |
| 183 | Format String Syntax |
| 184 | -------------------- |
| 185 | |
| 186 | The :meth:`str.format` method and the :class:`Formatter` class share the same |
| 187 | syntax for format strings (although in the case of :class:`Formatter`, |
| 188 | subclasses can define their own format string syntax.) |
| 189 | |
| 190 | Format strings contain "replacement fields" surrounded by curly braces ``{}``. |
| 191 | Anything that is not contained in braces is considered literal text, which is |
| 192 | copied unchanged to the output. If you need to include a brace character in the |
| 193 | literal text, it can be escaped by doubling: ``{{`` and ``}}``. |
| 194 | |
| 195 | The grammar for a replacement field is as follows: |
| 196 | |
| 197 | .. productionlist:: sf |
Georg Brandl | 2f3ed68 | 2009-09-01 07:42:40 +0000 | [diff] [blame] | 198 | replacement_field: "{" [`field_name`] ["!" `conversion`] [":" `format_spec`] "}" |
Eric Smith | c4cae32 | 2009-04-22 00:53:01 +0000 | [diff] [blame] | 199 | field_name: arg_name ("." `attribute_name` | "[" `element_index` "]")* |
| 200 | arg_name: (`identifier` | `integer`)? |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 201 | attribute_name: `identifier` |
Eric Smith | 2e9f202 | 2010-02-25 14:58:13 +0000 | [diff] [blame] | 202 | element_index: `integer` | `index_string` |
| 203 | index_string: <any source character except "]"> + |
Benjamin Peterson | 065ba70 | 2008-11-09 01:43:02 +0000 | [diff] [blame] | 204 | conversion: "r" | "s" | "a" |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 205 | format_spec: <described in the next section> |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 206 | |
Georg Brandl | 2f3ed68 | 2009-09-01 07:42:40 +0000 | [diff] [blame] | 207 | In less formal terms, the replacement field can start with a *field_name* that specifies |
Eric Smith | c4cae32 | 2009-04-22 00:53:01 +0000 | [diff] [blame] | 208 | the object whose value is to be formatted and inserted |
| 209 | into the output instead of the replacement field. |
| 210 | The *field_name* is optionally followed by a *conversion* field, which is |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 211 | preceded by an exclamation point ``'!'``, and a *format_spec*, which is preceded |
Eric Smith | c4cae32 | 2009-04-22 00:53:01 +0000 | [diff] [blame] | 212 | by a colon ``':'``. These specify a non-default format for the replacement value. |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 213 | |
Eric Smith | c4cae32 | 2009-04-22 00:53:01 +0000 | [diff] [blame] | 214 | The *field_name* itself begins with an *arg_name* that is either either a number or a |
| 215 | keyword. If it's a number, it refers to a positional argument, and if it's a keyword, |
| 216 | it refers to a named keyword argument. If the numerical arg_names in a format string |
| 217 | are 0, 1, 2, ... in sequence, they can all be omitted (not just some) |
| 218 | and the numbers 0, 1, 2, ... will be automatically inserted in that order. |
| 219 | The *arg_name* can be followed by any number of index or |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 220 | attribute expressions. An expression of the form ``'.name'`` selects the named |
| 221 | attribute using :func:`getattr`, while an expression of the form ``'[index]'`` |
| 222 | does an index lookup using :func:`__getitem__`. |
| 223 | |
| 224 | Some simple format string examples:: |
| 225 | |
| 226 | "First, thou shalt count to {0}" # References first positional argument |
Benjamin Peterson | 5879d41 | 2009-03-30 14:51:56 +0000 | [diff] [blame] | 227 | "Bring me a {}" # Implicitly references the first positional argument |
Georg Brandl | 2f3ed68 | 2009-09-01 07:42:40 +0000 | [diff] [blame] | 228 | "From {} to {}" # Same as "From {0} to {1}" |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 229 | "My quest is {name}" # References keyword argument 'name' |
| 230 | "Weight in tons {0.weight}" # 'weight' attribute of first positional arg |
| 231 | "Units destroyed: {players[0]}" # First element of keyword argument 'players'. |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 232 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 233 | The *conversion* field causes a type coercion before formatting. Normally, the |
| 234 | job of formatting a value is done by the :meth:`__format__` method of the value |
| 235 | itself. However, in some cases it is desirable to force a type to be formatted |
| 236 | as a string, overriding its own definition of formatting. By converting the |
| 237 | value to a string before calling :meth:`__format__`, the normal formatting logic |
| 238 | is bypassed. |
| 239 | |
Georg Brandl | 559e5d7 | 2008-06-11 18:37:52 +0000 | [diff] [blame] | 240 | Three conversion flags are currently supported: ``'!s'`` which calls :func:`str` |
| 241 | on the value, ``'!r'`` which calls :func:`repr` and ``'!a'`` which calls |
| 242 | :func:`ascii`. |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 243 | |
| 244 | Some examples:: |
| 245 | |
| 246 | "Harold's a clever {0!s}" # Calls str() on the argument first |
| 247 | "Bring out the holy {name!r}" # Calls repr() on the argument first |
Georg Brandl | 2f3ed68 | 2009-09-01 07:42:40 +0000 | [diff] [blame] | 248 | "More {!a}" # Calls ascii() on the argument first |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 249 | |
| 250 | The *format_spec* field contains a specification of how the value should be |
| 251 | presented, including such details as field width, alignment, padding, decimal |
Eric Smith | 0f7affe | 2010-02-15 11:57:31 +0000 | [diff] [blame] | 252 | precision and so on. Each value type can define its own "formatting |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 253 | mini-language" or interpretation of the *format_spec*. |
| 254 | |
| 255 | Most built-in types support a common formatting mini-language, which is |
| 256 | described in the next section. |
| 257 | |
| 258 | A *format_spec* field can also include nested replacement fields within it. |
| 259 | These nested replacement fields can contain only a field name; conversion flags |
| 260 | and format specifications are not allowed. The replacement fields within the |
| 261 | format_spec are substituted before the *format_spec* string is interpreted. |
| 262 | This allows the formatting of a value to be dynamically specified. |
| 263 | |
| 264 | For example, suppose you wanted to have a replacement field whose field width is |
| 265 | determined by another variable:: |
| 266 | |
| 267 | "A man with two {0:{1}}".format("noses", 10) |
| 268 | |
| 269 | This would first evaluate the inner replacement field, making the format string |
| 270 | effectively:: |
| 271 | |
| 272 | "A man with two {0:10}" |
| 273 | |
| 274 | Then the outer replacement field would be evaluated, producing:: |
| 275 | |
| 276 | "noses " |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 277 | |
Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 278 | Which is substituted into the string, yielding:: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 279 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 280 | "A man with two noses " |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 281 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 282 | (The extra space is because we specified a field width of 10, and because left |
| 283 | alignment is the default for strings.) |
| 284 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 285 | |
| 286 | .. _formatspec: |
| 287 | |
| 288 | Format Specification Mini-Language |
| 289 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 290 | |
| 291 | "Format specifications" are used within replacement fields contained within a |
| 292 | format string to define how individual values are presented (see |
Georg Brandl | 22b3431 | 2009-07-26 14:54:51 +0000 | [diff] [blame] | 293 | :ref:`formatstrings`.) They can also be passed directly to the built-in |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 294 | :func:`format` function. Each formattable type may define how the format |
| 295 | specification is to be interpreted. |
| 296 | |
| 297 | Most built-in types implement the following options for format specifications, |
| 298 | although some of the formatting options are only supported by the numeric types. |
| 299 | |
Eric Smith | 05c0774 | 2010-02-25 14:18:57 +0000 | [diff] [blame] | 300 | A general convention is that an empty format string (``""``) produces |
| 301 | the same result as if you had called :func:`str` on the value. A |
| 302 | non-empty format string typically modifies the result. |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 303 | |
| 304 | The general form of a *standard format specifier* is: |
| 305 | |
| 306 | .. productionlist:: sf |
Raymond Hettinger | 6db9470 | 2009-07-12 20:49:21 +0000 | [diff] [blame] | 307 | format_spec: [[`fill`]`align`][`sign`][#][0][`width`][,][.`precision`][`type`] |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 308 | fill: <a character other than '}'> |
| 309 | align: "<" | ">" | "=" | "^" |
| 310 | sign: "+" | "-" | " " |
| 311 | width: `integer` |
| 312 | precision: `integer` |
Eric Smith | 05c0774 | 2010-02-25 14:18:57 +0000 | [diff] [blame] | 313 | type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%" |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 314 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 315 | The *fill* character can be any character other than '}' (which signifies the |
| 316 | end of the field). The presence of a fill character is signaled by the *next* |
| 317 | character, which must be one of the alignment options. If the second character |
| 318 | of *format_spec* is not a valid alignment option, then it is assumed that both |
| 319 | the fill character and the alignment option are absent. |
| 320 | |
| 321 | The meaning of the various alignment options is as follows: |
| 322 | |
| 323 | +---------+----------------------------------------------------------+ |
| 324 | | Option | Meaning | |
| 325 | +=========+==========================================================+ |
| 326 | | ``'<'`` | Forces the field to be left-aligned within the available | |
| 327 | | | space (This is the default.) | |
| 328 | +---------+----------------------------------------------------------+ |
| 329 | | ``'>'`` | Forces the field to be right-aligned within the | |
| 330 | | | available space. | |
| 331 | +---------+----------------------------------------------------------+ |
| 332 | | ``'='`` | Forces the padding to be placed after the sign (if any) | |
| 333 | | | but before the digits. This is used for printing fields | |
| 334 | | | in the form '+000000120'. This alignment option is only | |
| 335 | | | valid for numeric types. | |
| 336 | +---------+----------------------------------------------------------+ |
| 337 | | ``'^'`` | Forces the field to be centered within the available | |
| 338 | | | space. | |
| 339 | +---------+----------------------------------------------------------+ |
| 340 | |
| 341 | Note that unless a minimum field width is defined, the field width will always |
| 342 | be the same size as the data to fill it, so that the alignment option has no |
| 343 | meaning in this case. |
| 344 | |
| 345 | The *sign* option is only valid for number types, and can be one of the |
| 346 | following: |
| 347 | |
| 348 | +---------+----------------------------------------------------------+ |
| 349 | | Option | Meaning | |
| 350 | +=========+==========================================================+ |
| 351 | | ``'+'`` | indicates that a sign should be used for both | |
| 352 | | | positive as well as negative numbers. | |
| 353 | +---------+----------------------------------------------------------+ |
| 354 | | ``'-'`` | indicates that a sign should be used only for negative | |
| 355 | | | numbers (this is the default behavior). | |
| 356 | +---------+----------------------------------------------------------+ |
| 357 | | space | indicates that a leading space should be used on | |
| 358 | | | positive numbers, and a minus sign on negative numbers. | |
| 359 | +---------+----------------------------------------------------------+ |
| 360 | |
Benjamin Peterson | d7b0328 | 2008-09-13 15:58:53 +0000 | [diff] [blame] | 361 | The ``'#'`` option is only valid for integers, and only for binary, octal, or |
| 362 | hexadecimal output. If present, it specifies that the output will be prefixed |
| 363 | by ``'0b'``, ``'0o'``, or ``'0x'``, respectively. |
Eric Smith | d68af8f | 2008-07-16 00:15:35 +0000 | [diff] [blame] | 364 | |
Raymond Hettinger | 6db9470 | 2009-07-12 20:49:21 +0000 | [diff] [blame] | 365 | The ``','`` option signals the use of a comma for a thousands separator. |
| 366 | For a locale aware separator, use the ``'n'`` integer presentation type |
| 367 | instead. |
| 368 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 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 | If the *width* field is preceded by a zero (``'0'``) character, this enables |
| 373 | zero-padding. This is equivalent to an *alignment* type of ``'='`` and a *fill* |
| 374 | character of ``'0'``. |
| 375 | |
| 376 | The *precision* is a decimal number indicating how many digits should be |
Georg Brandl | 3dbca81 | 2008-07-23 16:10:53 +0000 | [diff] [blame] | 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 |
Eric Smith | e5fffc7 | 2009-05-07 19:38:09 +0000 | [diff] [blame] | 381 | used from the field content. The *precision* is not allowed for integer values. |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 382 | |
| 383 | Finally, the *type* determines how the data should be presented. |
| 384 | |
Eric Smith | 05c0774 | 2010-02-25 14:18:57 +0000 | [diff] [blame] | 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 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 396 | The available integer presentation types are: |
| 397 | |
| 398 | +---------+----------------------------------------------------------+ |
| 399 | | Type | Meaning | |
| 400 | +=========+==========================================================+ |
Eric Smith | d68af8f | 2008-07-16 00:15:35 +0000 | [diff] [blame] | 401 | | ``'b'`` | Binary format. Outputs the number in base 2. | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 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 | +---------+----------------------------------------------------------+ |
Eric Smith | 5e18a20 | 2008-05-12 10:01:24 +0000 | [diff] [blame] | 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 | +---------+----------------------------------------------------------+ |
Georg Brandl | 3dbca81 | 2008-07-23 16:10:53 +0000 | [diff] [blame] | 420 | | None | The same as ``'d'``. | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 421 | +---------+----------------------------------------------------------+ |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 422 | |
Eric Smith | 05c0774 | 2010-02-25 14:18:57 +0000 | [diff] [blame] | 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 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 428 | The available presentation types for floating point and decimal values are: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 429 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 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 | +---------+----------------------------------------------------------+ |
Eric Smith | 22b85b3 | 2008-07-17 19:18:29 +0000 | [diff] [blame] | 436 | | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an | |
| 437 | | | upper case 'E' as the separator character. | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 438 | +---------+----------------------------------------------------------+ |
| 439 | | ``'f'`` | Fixed point. Displays the number as a fixed-point | |
| 440 | | | number. | |
| 441 | +---------+----------------------------------------------------------+ |
Eric Smith | 741191f | 2009-05-06 13:08:15 +0000 | [diff] [blame] | 442 | | ``'F'`` | Fixed point. Same as ``'f'``, but converts ``nan`` to | |
| 443 | | | ``NAN`` and ``inf`` to ``INF``. | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 444 | +---------+----------------------------------------------------------+ |
Mark Dickinson | c70614f | 2009-10-08 20:05:48 +0000 | [diff] [blame] | 445 | | ``'g'`` | General format. For a given precision ``p >= 1``, | |
| 446 | | | this rounds the number to ``p`` significant digits and | |
| 447 | | | then formats the result in either fixed-point format | |
| 448 | | | or in scientific notation, depending on its magnitude. | |
| 449 | | | | |
| 450 | | | The precise rules are as follows: suppose that the | |
| 451 | | | result formatted with presentation type ``'e'`` and | |
| 452 | | | precision ``p-1`` would have exponent ``exp``. Then | |
| 453 | | | if ``-4 <= exp < p``, the number is formatted | |
| 454 | | | with presentation type ``'f'`` and precision | |
| 455 | | | ``p-1-exp``. Otherwise, the number is formatted | |
| 456 | | | with presentation type ``'e'`` and precision ``p-1``. | |
| 457 | | | In both cases insignificant trailing zeros are removed | |
| 458 | | | from the significand, and the decimal point is also | |
| 459 | | | removed if there are no remaining digits following it. | |
| 460 | | | | |
| 461 | | | Postive and negative infinity, positive and negative | |
| 462 | | | zero, and nans, are formatted as ``inf``, ``-inf``, | |
| 463 | | | ``0``, ``-0`` and ``nan`` respectively, regardless of | |
| 464 | | | the precision. | |
| 465 | | | | |
| 466 | | | A precision of ``0`` is treated as equivalent to a | |
| 467 | | | precision of ``1``. | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 468 | +---------+----------------------------------------------------------+ |
| 469 | | ``'G'`` | General format. Same as ``'g'`` except switches to | |
Mark Dickinson | c70614f | 2009-10-08 20:05:48 +0000 | [diff] [blame] | 470 | | | ``'E'`` if the number gets too large. The | |
| 471 | | | representations of infinity and NaN are uppercased, too. | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 472 | +---------+----------------------------------------------------------+ |
| 473 | | ``'n'`` | Number. This is the same as ``'g'``, except that it uses | |
| 474 | | | the current locale setting to insert the appropriate | |
| 475 | | | number separator characters. | |
| 476 | +---------+----------------------------------------------------------+ |
| 477 | | ``'%'`` | Percentage. Multiplies the number by 100 and displays | |
| 478 | | | in fixed (``'f'``) format, followed by a percent sign. | |
| 479 | +---------+----------------------------------------------------------+ |
Eric Smith | 3bef15b | 2009-05-05 17:19:46 +0000 | [diff] [blame] | 480 | | None | Similar to ``'g'``, except with at least one digit past | |
| 481 | | | the decimal point and a default precision of 12. This is | |
| 482 | | | intended to match :func:`str`, except you can add the | |
| 483 | | | other format modifiers. | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 484 | +---------+----------------------------------------------------------+ |
| 485 | |
| 486 | |
| 487 | .. _template-strings: |
| 488 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 489 | Template strings |
| 490 | ---------------- |
| 491 | |
| 492 | Templates provide simpler string substitutions as described in :pep:`292`. |
| 493 | Instead of the normal ``%``\ -based substitutions, Templates support ``$``\ |
| 494 | -based substitutions, using the following rules: |
| 495 | |
| 496 | * ``$$`` is an escape; it is replaced with a single ``$``. |
| 497 | |
| 498 | * ``$identifier`` names a substitution placeholder matching a mapping key of |
| 499 | ``"identifier"``. By default, ``"identifier"`` must spell a Python |
| 500 | identifier. The first non-identifier character after the ``$`` character |
| 501 | terminates this placeholder specification. |
| 502 | |
| 503 | * ``${identifier}`` is equivalent to ``$identifier``. It is required when valid |
| 504 | identifier characters follow the placeholder but are not part of the |
| 505 | placeholder, such as ``"${noun}ification"``. |
| 506 | |
| 507 | Any other appearance of ``$`` in the string will result in a :exc:`ValueError` |
| 508 | being raised. |
| 509 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 510 | The :mod:`string` module provides a :class:`Template` class that implements |
| 511 | these rules. The methods of :class:`Template` are: |
| 512 | |
| 513 | |
| 514 | .. class:: Template(template) |
| 515 | |
| 516 | The constructor takes a single argument which is the template string. |
| 517 | |
| 518 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 519 | .. method:: substitute(mapping, **kwds) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 520 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 521 | Performs the template substitution, returning a new string. *mapping* is |
| 522 | any dictionary-like object with keys that match the placeholders in the |
| 523 | template. Alternatively, you can provide keyword arguments, where the |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 524 | keywords are the placeholders. When both *mapping* and *kwds* are given |
| 525 | and there are duplicates, the placeholders from *kwds* take precedence. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 526 | |
| 527 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 528 | .. method:: safe_substitute(mapping, **kwds) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 529 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 530 | Like :meth:`substitute`, except that if placeholders are missing from |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 531 | *mapping* and *kwds*, instead of raising a :exc:`KeyError` exception, the |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 532 | original placeholder will appear in the resulting string intact. Also, |
| 533 | unlike with :meth:`substitute`, any other appearances of the ``$`` will |
| 534 | simply return ``$`` instead of raising :exc:`ValueError`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 535 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 536 | While other exceptions may still occur, this method is called "safe" |
| 537 | because substitutions always tries to return a usable string instead of |
| 538 | raising an exception. In another sense, :meth:`safe_substitute` may be |
| 539 | anything other than safe, since it will silently ignore malformed |
| 540 | templates containing dangling delimiters, unmatched braces, or |
| 541 | placeholders that are not valid Python identifiers. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 542 | |
Benjamin Peterson | 2021100 | 2009-11-25 18:34:42 +0000 | [diff] [blame] | 543 | :class:`Template` instances also provide one public data attribute: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 544 | |
Benjamin Peterson | 2021100 | 2009-11-25 18:34:42 +0000 | [diff] [blame] | 545 | .. attribute:: template |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 546 | |
Benjamin Peterson | 2021100 | 2009-11-25 18:34:42 +0000 | [diff] [blame] | 547 | This is the object passed to the constructor's *template* argument. In |
| 548 | general, you shouldn't change it, but read-only access is not enforced. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 549 | |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 550 | Here is an example of how to use a Template: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 551 | |
| 552 | >>> from string import Template |
| 553 | >>> s = Template('$who likes $what') |
| 554 | >>> s.substitute(who='tim', what='kung pao') |
| 555 | 'tim likes kung pao' |
| 556 | >>> d = dict(who='tim') |
| 557 | >>> Template('Give $who $100').substitute(d) |
| 558 | Traceback (most recent call last): |
| 559 | [...] |
| 560 | ValueError: Invalid placeholder in string: line 1, col 10 |
| 561 | >>> Template('$who likes $what').substitute(d) |
| 562 | Traceback (most recent call last): |
| 563 | [...] |
| 564 | KeyError: 'what' |
| 565 | >>> Template('$who likes $what').safe_substitute(d) |
| 566 | 'tim likes $what' |
| 567 | |
| 568 | Advanced usage: you can derive subclasses of :class:`Template` to customize the |
| 569 | placeholder syntax, delimiter character, or the entire regular expression used |
| 570 | to parse template strings. To do this, you can override these class attributes: |
| 571 | |
| 572 | * *delimiter* -- This is the literal string describing a placeholder introducing |
| 573 | delimiter. The default value ``$``. Note that this should *not* be a regular |
| 574 | expression, as the implementation will call :meth:`re.escape` on this string as |
| 575 | needed. |
| 576 | |
| 577 | * *idpattern* -- This is the regular expression describing the pattern for |
| 578 | non-braced placeholders (the braces will be added automatically as |
| 579 | appropriate). The default value is the regular expression |
| 580 | ``[_a-z][_a-z0-9]*``. |
| 581 | |
| 582 | Alternatively, you can provide the entire regular expression pattern by |
| 583 | overriding the class attribute *pattern*. If you do this, the value must be a |
| 584 | regular expression object with four named capturing groups. The capturing |
| 585 | groups correspond to the rules given above, along with the invalid placeholder |
| 586 | rule: |
| 587 | |
| 588 | * *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the |
| 589 | default pattern. |
| 590 | |
| 591 | * *named* -- This group matches the unbraced placeholder name; it should not |
| 592 | include the delimiter in capturing group. |
| 593 | |
| 594 | * *braced* -- This group matches the brace enclosed placeholder name; it should |
| 595 | not include either the delimiter or braces in the capturing group. |
| 596 | |
| 597 | * *invalid* -- This group matches any other delimiter pattern (usually a single |
| 598 | delimiter), and it should appear last in the regular expression. |
| 599 | |
| 600 | |
Georg Brandl | abc3877 | 2009-04-12 15:51:51 +0000 | [diff] [blame] | 601 | Helper functions |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 602 | ---------------- |
| 603 | |
Georg Brandl | 10430ad | 2009-09-26 20:59:11 +0000 | [diff] [blame] | 604 | .. function:: capwords(s, sep=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 605 | |
Ezio Melotti | a40bdda | 2009-09-26 12:33:22 +0000 | [diff] [blame] | 606 | Split the argument into words using :meth:`str.split`, capitalize each word |
| 607 | using :meth:`str.capitalize`, and join the capitalized words using |
| 608 | :meth:`str.join`. If the optional second argument *sep* is absent |
| 609 | or ``None``, runs of whitespace characters are replaced by a single space |
| 610 | and leading and trailing whitespace are removed, otherwise *sep* is used to |
| 611 | split and join the words. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 612 | |