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