/python/library/string.html
HTML | 638 lines | 608 code | 30 blank | 0 comment | 0 complexity | d9caf2b981452a85cd0b811b46104a34 MD5 | raw file
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-
- <title>7.1. string — Common string operations — Python v2.7.3 documentation</title>
- <link rel="stylesheet" href="../_static/default.css" type="text/css" />
- <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
- <script type="text/javascript">
- var DOCUMENTATION_OPTIONS = {
- URL_ROOT: '../',
- VERSION: '2.7.3',
- COLLAPSE_INDEX: false,
- FILE_SUFFIX: '.html',
- HAS_SOURCE: true
- };
- </script>
- <script type="text/javascript" src="../_static/jquery.js"></script>
- <script type="text/javascript" src="../_static/underscore.js"></script>
- <script type="text/javascript" src="../_static/doctools.js"></script>
- <script type="text/javascript" src="../_static/sidebar.js"></script>
- <link rel="search" type="application/opensearchdescription+xml"
- title="Search within Python v2.7.3 documentation"
- href="../_static/opensearch.xml"/>
- <link rel="author" title="About these documents" href="../about.html" />
- <link rel="copyright" title="Copyright" href="../copyright.html" />
- <link rel="top" title="Python v2.7.3 documentation" href="../index.html" />
- <link rel="up" title="7. String Services" href="strings.html" />
- <link rel="next" title="7.2. re — Regular expression operations" href="re.html" />
- <link rel="prev" title="7. String Services" href="strings.html" />
- <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
- <script type="text/javascript" src="../_static/copybutton.js"></script>
- <script type="text/javascript" src="../_static/version_switch.js"></script>
-
- </head>
- <body>
- <div class="related">
- <h3>Navigation</h3>
- <ul>
- <li class="right" style="margin-right: 10px">
- <a href="../genindex.html" title="General Index"
- accesskey="I">index</a></li>
- <li class="right" >
- <a href="../py-modindex.html" title="Python Module Index"
- >modules</a> |</li>
- <li class="right" >
- <a href="re.html" title="7.2. re — Regular expression operations"
- accesskey="N">next</a> |</li>
- <li class="right" >
- <a href="strings.html" title="7. String Services"
- accesskey="P">previous</a> |</li>
- <li><img src="../_static/py.png" alt=""
- style="vertical-align: middle; margin-top: -1px"/></li>
- <li><a href="http://www.python.org/">Python</a> »</li>
- <li>
- <span class="version_switcher_placeholder">2.7.3</span>
- <a href="../index.html">Documentation</a> »
- </li>
- <li><a href="index.html" >The Python Standard Library</a> »</li>
- <li><a href="strings.html" accesskey="U">7. String Services</a> »</li>
- </ul>
- </div>
- <div class="document">
- <div class="documentwrapper">
- <div class="bodywrapper">
- <div class="body">
-
- <div class="section" id="module-string">
- <span id="string-common-string-operations"></span><h1>7.1. <a class="reference internal" href="#module-string" title="string: Common string operations."><tt class="xref py py-mod docutils literal"><span class="pre">string</span></tt></a> — Common string operations<a class="headerlink" href="#module-string" title="Permalink to this headline">¶</a></h1>
- <p id="index-0"><strong>Source code:</strong> <a class="reference external" href="http://hg.python.org/cpython/file/2.7/Lib/string.py">Lib/string.py</a></p>
- <hr class="docutils" />
- <p>The <a class="reference internal" href="#module-string" title="string: Common string operations."><tt class="xref py py-mod docutils literal"><span class="pre">string</span></tt></a> module contains a number of useful constants and
- classes, as well as some deprecated legacy functions that are also
- available as methods on strings. In addition, Python’s built-in string
- classes support the sequence type methods described in the
- <a class="reference internal" href="stdtypes.html#typesseq"><em>Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange</em></a> section, and also the string-specific methods described
- in the <a class="reference internal" href="stdtypes.html#string-methods"><em>String Methods</em></a> section. To output formatted strings use
- template strings or the <tt class="docutils literal"><span class="pre">%</span></tt> operator described in the
- <a class="reference internal" href="stdtypes.html#string-formatting"><em>String Formatting Operations</em></a> section. Also, see the <a class="reference internal" href="re.html#module-re" title="re: Regular expression operations."><tt class="xref py py-mod docutils literal"><span class="pre">re</span></tt></a> module for
- string functions based on regular expressions.</p>
- <div class="section" id="string-constants">
- <h2>7.1.1. String constants<a class="headerlink" href="#string-constants" title="Permalink to this headline">¶</a></h2>
- <p>The constants defined in this module are:</p>
- <dl class="data">
- <dt id="string.ascii_letters">
- <tt class="descclassname">string.</tt><tt class="descname">ascii_letters</tt><a class="headerlink" href="#string.ascii_letters" title="Permalink to this definition">¶</a></dt>
- <dd><p>The concatenation of the <a class="reference internal" href="#string.ascii_lowercase" title="string.ascii_lowercase"><tt class="xref py py-const docutils literal"><span class="pre">ascii_lowercase</span></tt></a> and <a class="reference internal" href="#string.ascii_uppercase" title="string.ascii_uppercase"><tt class="xref py py-const docutils literal"><span class="pre">ascii_uppercase</span></tt></a>
- constants described below. This value is not locale-dependent.</p>
- </dd></dl>
- <dl class="data">
- <dt id="string.ascii_lowercase">
- <tt class="descclassname">string.</tt><tt class="descname">ascii_lowercase</tt><a class="headerlink" href="#string.ascii_lowercase" title="Permalink to this definition">¶</a></dt>
- <dd><p>The lowercase letters <tt class="docutils literal"><span class="pre">'abcdefghijklmnopqrstuvwxyz'</span></tt>. This value is not
- locale-dependent and will not change.</p>
- </dd></dl>
- <dl class="data">
- <dt id="string.ascii_uppercase">
- <tt class="descclassname">string.</tt><tt class="descname">ascii_uppercase</tt><a class="headerlink" href="#string.ascii_uppercase" title="Permalink to this definition">¶</a></dt>
- <dd><p>The uppercase letters <tt class="docutils literal"><span class="pre">'ABCDEFGHIJKLMNOPQRSTUVWXYZ'</span></tt>. This value is not
- locale-dependent and will not change.</p>
- </dd></dl>
- <dl class="data">
- <dt id="string.digits">
- <tt class="descclassname">string.</tt><tt class="descname">digits</tt><a class="headerlink" href="#string.digits" title="Permalink to this definition">¶</a></dt>
- <dd><p>The string <tt class="docutils literal"><span class="pre">'0123456789'</span></tt>.</p>
- </dd></dl>
- <dl class="data">
- <dt id="string.hexdigits">
- <tt class="descclassname">string.</tt><tt class="descname">hexdigits</tt><a class="headerlink" href="#string.hexdigits" title="Permalink to this definition">¶</a></dt>
- <dd><p>The string <tt class="docutils literal"><span class="pre">'0123456789abcdefABCDEF'</span></tt>.</p>
- </dd></dl>
- <dl class="data">
- <dt id="string.letters">
- <tt class="descclassname">string.</tt><tt class="descname">letters</tt><a class="headerlink" href="#string.letters" title="Permalink to this definition">¶</a></dt>
- <dd><p>The concatenation of the strings <a class="reference internal" href="#string.lowercase" title="string.lowercase"><tt class="xref py py-const docutils literal"><span class="pre">lowercase</span></tt></a> and <a class="reference internal" href="#string.uppercase" title="string.uppercase"><tt class="xref py py-const docutils literal"><span class="pre">uppercase</span></tt></a>
- described below. The specific value is locale-dependent, and will be updated
- when <a class="reference internal" href="locale.html#locale.setlocale" title="locale.setlocale"><tt class="xref py py-func docutils literal"><span class="pre">locale.setlocale()</span></tt></a> is called.</p>
- </dd></dl>
- <dl class="data">
- <dt id="string.lowercase">
- <tt class="descclassname">string.</tt><tt class="descname">lowercase</tt><a class="headerlink" href="#string.lowercase" title="Permalink to this definition">¶</a></dt>
- <dd><p>A string containing all the characters that are considered lowercase letters.
- On most systems this is the string <tt class="docutils literal"><span class="pre">'abcdefghijklmnopqrstuvwxyz'</span></tt>. The
- specific value is locale-dependent, and will be updated when
- <a class="reference internal" href="locale.html#locale.setlocale" title="locale.setlocale"><tt class="xref py py-func docutils literal"><span class="pre">locale.setlocale()</span></tt></a> is called.</p>
- </dd></dl>
- <dl class="data">
- <dt id="string.octdigits">
- <tt class="descclassname">string.</tt><tt class="descname">octdigits</tt><a class="headerlink" href="#string.octdigits" title="Permalink to this definition">¶</a></dt>
- <dd><p>The string <tt class="docutils literal"><span class="pre">'01234567'</span></tt>.</p>
- </dd></dl>
- <dl class="data">
- <dt id="string.punctuation">
- <tt class="descclassname">string.</tt><tt class="descname">punctuation</tt><a class="headerlink" href="#string.punctuation" title="Permalink to this definition">¶</a></dt>
- <dd><p>String of ASCII characters which are considered punctuation characters in the
- <tt class="docutils literal"><span class="pre">C</span></tt> locale.</p>
- </dd></dl>
- <dl class="data">
- <dt id="string.printable">
- <tt class="descclassname">string.</tt><tt class="descname">printable</tt><a class="headerlink" href="#string.printable" title="Permalink to this definition">¶</a></dt>
- <dd><p>String of characters which are considered printable. This is a combination of
- <a class="reference internal" href="#string.digits" title="string.digits"><tt class="xref py py-const docutils literal"><span class="pre">digits</span></tt></a>, <a class="reference internal" href="#string.letters" title="string.letters"><tt class="xref py py-const docutils literal"><span class="pre">letters</span></tt></a>, <a class="reference internal" href="#string.punctuation" title="string.punctuation"><tt class="xref py py-const docutils literal"><span class="pre">punctuation</span></tt></a>, and
- <a class="reference internal" href="#string.whitespace" title="string.whitespace"><tt class="xref py py-const docutils literal"><span class="pre">whitespace</span></tt></a>.</p>
- </dd></dl>
- <dl class="data">
- <dt id="string.uppercase">
- <tt class="descclassname">string.</tt><tt class="descname">uppercase</tt><a class="headerlink" href="#string.uppercase" title="Permalink to this definition">¶</a></dt>
- <dd><p>A string containing all the characters that are considered uppercase letters.
- On most systems this is the string <tt class="docutils literal"><span class="pre">'ABCDEFGHIJKLMNOPQRSTUVWXYZ'</span></tt>. The
- specific value is locale-dependent, and will be updated when
- <a class="reference internal" href="locale.html#locale.setlocale" title="locale.setlocale"><tt class="xref py py-func docutils literal"><span class="pre">locale.setlocale()</span></tt></a> is called.</p>
- </dd></dl>
- <dl class="data">
- <dt id="string.whitespace">
- <tt class="descclassname">string.</tt><tt class="descname">whitespace</tt><a class="headerlink" href="#string.whitespace" title="Permalink to this definition">¶</a></dt>
- <dd><p>A string containing all characters that are considered whitespace. On most
- systems this includes the characters space, tab, linefeed, return, formfeed, and
- vertical tab.</p>
- </dd></dl>
- </div>
- <div class="section" id="string-formatting">
- <span id="new-string-formatting"></span><h2>7.1.2. String Formatting<a class="headerlink" href="#string-formatting" title="Permalink to this headline">¶</a></h2>
- <p class="versionadded">
- <span class="versionmodified">New in version 2.6.</span></p>
- <p>The built-in str and unicode classes provide the ability
- to do complex variable substitutions and value formatting via the
- <a class="reference internal" href="stdtypes.html#str.format" title="str.format"><tt class="xref py py-meth docutils literal"><span class="pre">str.format()</span></tt></a> method described in <span class="target" id="index-1"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-3101"><strong>PEP 3101</strong></a>. The <a class="reference internal" href="#string.Formatter" title="string.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a>
- class in the <a class="reference internal" href="#module-string" title="string: Common string operations."><tt class="xref py py-mod docutils literal"><span class="pre">string</span></tt></a> module allows you to create and customize your own
- string formatting behaviors using the same implementation as the built-in
- <a class="reference internal" href="functions.html#format" title="format"><tt class="xref py py-meth docutils literal"><span class="pre">format()</span></tt></a> method.</p>
- <dl class="class">
- <dt id="string.Formatter">
- <em class="property">class </em><tt class="descclassname">string.</tt><tt class="descname">Formatter</tt><a class="headerlink" href="#string.Formatter" title="Permalink to this definition">¶</a></dt>
- <dd><p>The <a class="reference internal" href="#string.Formatter" title="string.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a> class has the following public methods:</p>
- <dl class="method">
- <dt id="string.Formatter.format">
- <tt class="descname">format</tt><big>(</big><em>format_string</em>, <em>*args</em>, <em>**kwargs</em><big>)</big><a class="headerlink" href="#string.Formatter.format" title="Permalink to this definition">¶</a></dt>
- <dd><p><a class="reference internal" href="functions.html#format" title="format"><tt class="xref py py-meth docutils literal"><span class="pre">format()</span></tt></a> is the primary API method. It takes a format string and
- an arbitrary set of positional and keyword arguments.
- <a class="reference internal" href="functions.html#format" title="format"><tt class="xref py py-meth docutils literal"><span class="pre">format()</span></tt></a> is just a wrapper that calls <a class="reference internal" href="#string.Formatter.vformat" title="string.Formatter.vformat"><tt class="xref py py-meth docutils literal"><span class="pre">vformat()</span></tt></a>.</p>
- </dd></dl>
- <dl class="method">
- <dt id="string.Formatter.vformat">
- <tt class="descname">vformat</tt><big>(</big><em>format_string</em>, <em>args</em>, <em>kwargs</em><big>)</big><a class="headerlink" href="#string.Formatter.vformat" title="Permalink to this definition">¶</a></dt>
- <dd><p>This function does the actual work of formatting. It is exposed as a
- separate function for cases where you want to pass in a predefined
- dictionary of arguments, rather than unpacking and repacking the
- dictionary as individual arguments using the <tt class="docutils literal"><span class="pre">*args</span></tt> and <tt class="docutils literal"><span class="pre">**kwargs</span></tt>
- syntax. <a class="reference internal" href="#string.Formatter.vformat" title="string.Formatter.vformat"><tt class="xref py py-meth docutils literal"><span class="pre">vformat()</span></tt></a> does the work of breaking up the format string
- into character data and replacement fields. It calls the various
- methods described below.</p>
- </dd></dl>
- <p>In addition, the <a class="reference internal" href="#string.Formatter" title="string.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a> defines a number of methods that are
- intended to be replaced by subclasses:</p>
- <dl class="method">
- <dt id="string.Formatter.parse">
- <tt class="descname">parse</tt><big>(</big><em>format_string</em><big>)</big><a class="headerlink" href="#string.Formatter.parse" title="Permalink to this definition">¶</a></dt>
- <dd><p>Loop over the format_string and return an iterable of tuples
- (<em>literal_text</em>, <em>field_name</em>, <em>format_spec</em>, <em>conversion</em>). This is used
- by <a class="reference internal" href="#string.Formatter.vformat" title="string.Formatter.vformat"><tt class="xref py py-meth docutils literal"><span class="pre">vformat()</span></tt></a> to break the string into either literal text, or
- replacement fields.</p>
- <p>The values in the tuple conceptually represent a span of literal text
- followed by a single replacement field. If there is no literal text
- (which can happen if two replacement fields occur consecutively), then
- <em>literal_text</em> will be a zero-length string. If there is no replacement
- field, then the values of <em>field_name</em>, <em>format_spec</em> and <em>conversion</em>
- will be <tt class="xref docutils literal"><span class="pre">None</span></tt>.</p>
- </dd></dl>
- <dl class="method">
- <dt id="string.Formatter.get_field">
- <tt class="descname">get_field</tt><big>(</big><em>field_name</em>, <em>args</em>, <em>kwargs</em><big>)</big><a class="headerlink" href="#string.Formatter.get_field" title="Permalink to this definition">¶</a></dt>
- <dd><p>Given <em>field_name</em> as returned by <a class="reference internal" href="#string.Formatter.parse" title="string.Formatter.parse"><tt class="xref py py-meth docutils literal"><span class="pre">parse()</span></tt></a> (see above), convert it to
- an object to be formatted. Returns a tuple (obj, used_key). The default
- version takes strings of the form defined in <span class="target" id="index-2"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-3101"><strong>PEP 3101</strong></a>, such as
- “0[name]” or “label.title”. <em>args</em> and <em>kwargs</em> are as passed in to
- <a class="reference internal" href="#string.Formatter.vformat" title="string.Formatter.vformat"><tt class="xref py py-meth docutils literal"><span class="pre">vformat()</span></tt></a>. The return value <em>used_key</em> has the same meaning as the
- <em>key</em> parameter to <a class="reference internal" href="#string.Formatter.get_value" title="string.Formatter.get_value"><tt class="xref py py-meth docutils literal"><span class="pre">get_value()</span></tt></a>.</p>
- </dd></dl>
- <dl class="method">
- <dt id="string.Formatter.get_value">
- <tt class="descname">get_value</tt><big>(</big><em>key</em>, <em>args</em>, <em>kwargs</em><big>)</big><a class="headerlink" href="#string.Formatter.get_value" title="Permalink to this definition">¶</a></dt>
- <dd><p>Retrieve a given field value. The <em>key</em> argument will be either an
- integer or a string. If it is an integer, it represents the index of the
- positional argument in <em>args</em>; if it is a string, then it represents a
- named argument in <em>kwargs</em>.</p>
- <p>The <em>args</em> parameter is set to the list of positional arguments to
- <a class="reference internal" href="#string.Formatter.vformat" title="string.Formatter.vformat"><tt class="xref py py-meth docutils literal"><span class="pre">vformat()</span></tt></a>, and the <em>kwargs</em> parameter is set to the dictionary of
- keyword arguments.</p>
- <p>For compound field names, these functions are only called for the first
- component of the field name; Subsequent components are handled through
- normal attribute and indexing operations.</p>
- <p>So for example, the field expression ‘0.name’ would cause
- <a class="reference internal" href="#string.Formatter.get_value" title="string.Formatter.get_value"><tt class="xref py py-meth docutils literal"><span class="pre">get_value()</span></tt></a> to be called with a <em>key</em> argument of 0. The <tt class="docutils literal"><span class="pre">name</span></tt>
- attribute will be looked up after <a class="reference internal" href="#string.Formatter.get_value" title="string.Formatter.get_value"><tt class="xref py py-meth docutils literal"><span class="pre">get_value()</span></tt></a> returns by calling the
- built-in <a class="reference internal" href="functions.html#getattr" title="getattr"><tt class="xref py py-func docutils literal"><span class="pre">getattr()</span></tt></a> function.</p>
- <p>If the index or keyword refers to an item that does not exist, then an
- <a class="reference internal" href="exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><tt class="xref py py-exc docutils literal"><span class="pre">IndexError</span></tt></a> or <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><tt class="xref py py-exc docutils literal"><span class="pre">KeyError</span></tt></a> should be raised.</p>
- </dd></dl>
- <dl class="method">
- <dt id="string.Formatter.check_unused_args">
- <tt class="descname">check_unused_args</tt><big>(</big><em>used_args</em>, <em>args</em>, <em>kwargs</em><big>)</big><a class="headerlink" href="#string.Formatter.check_unused_args" title="Permalink to this definition">¶</a></dt>
- <dd><p>Implement checking for unused arguments if desired. The arguments to this
- function is the set of all argument keys that were actually referred to in
- the format string (integers for positional arguments, and strings for
- named arguments), and a reference to the <em>args</em> and <em>kwargs</em> that was
- passed to vformat. The set of unused args can be calculated from these
- parameters. <a class="reference internal" href="#string.Formatter.check_unused_args" title="string.Formatter.check_unused_args"><tt class="xref py py-meth docutils literal"><span class="pre">check_unused_args()</span></tt></a> is assumed to raise an exception if
- the check fails.</p>
- </dd></dl>
- <dl class="method">
- <dt id="string.Formatter.format_field">
- <tt class="descname">format_field</tt><big>(</big><em>value</em>, <em>format_spec</em><big>)</big><a class="headerlink" href="#string.Formatter.format_field" title="Permalink to this definition">¶</a></dt>
- <dd><p><a class="reference internal" href="#string.Formatter.format_field" title="string.Formatter.format_field"><tt class="xref py py-meth docutils literal"><span class="pre">format_field()</span></tt></a> simply calls the global <a class="reference internal" href="functions.html#format" title="format"><tt class="xref py py-func docutils literal"><span class="pre">format()</span></tt></a> built-in. The
- method is provided so that subclasses can override it.</p>
- </dd></dl>
- <dl class="method">
- <dt id="string.Formatter.convert_field">
- <tt class="descname">convert_field</tt><big>(</big><em>value</em>, <em>conversion</em><big>)</big><a class="headerlink" href="#string.Formatter.convert_field" title="Permalink to this definition">¶</a></dt>
- <dd><p>Converts the value (returned by <a class="reference internal" href="#string.Formatter.get_field" title="string.Formatter.get_field"><tt class="xref py py-meth docutils literal"><span class="pre">get_field()</span></tt></a>) given a conversion type
- (as in the tuple returned by the <a class="reference internal" href="#string.Formatter.parse" title="string.Formatter.parse"><tt class="xref py py-meth docutils literal"><span class="pre">parse()</span></tt></a> method). The default
- version understands ‘s’ (str), ‘r’ (repr) and ‘a’ (ascii) conversion
- types.</p>
- </dd></dl>
- </dd></dl>
- </div>
- <div class="section" id="format-string-syntax">
- <span id="formatstrings"></span><h2>7.1.3. Format String Syntax<a class="headerlink" href="#format-string-syntax" title="Permalink to this headline">¶</a></h2>
- <p>The <a class="reference internal" href="stdtypes.html#str.format" title="str.format"><tt class="xref py py-meth docutils literal"><span class="pre">str.format()</span></tt></a> method and the <a class="reference internal" href="#string.Formatter" title="string.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a> class share the same
- syntax for format strings (although in the case of <a class="reference internal" href="#string.Formatter" title="string.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a>,
- subclasses can define their own format string syntax).</p>
- <p>Format strings contain “replacement fields” surrounded by curly braces <tt class="docutils literal"><span class="pre">{}</span></tt>.
- Anything that is not contained in braces is considered literal text, which is
- copied unchanged to the output. If you need to include a brace character in the
- literal text, it can be escaped by doubling: <tt class="docutils literal"><span class="pre">{{</span></tt> and <tt class="docutils literal"><span class="pre">}}</span></tt>.</p>
- <p>The grammar for a replacement field is as follows:</p>
- <blockquote>
- <div><pre>
- <strong id="grammar-token-replacement_field">replacement_field</strong> ::= "{" [<a class="reference internal" href="#grammar-token-field_name"><tt class="xref docutils literal"><span class="pre">field_name</span></tt></a>] ["!" <a class="reference internal" href="#grammar-token-conversion"><tt class="xref docutils literal"><span class="pre">conversion</span></tt></a>] [":" <a class="reference internal" href="#grammar-token-format_spec"><tt class="xref docutils literal"><span class="pre">format_spec</span></tt></a>] "}"
- <strong id="grammar-token-field_name">field_name </strong> ::= arg_name ("." <a class="reference internal" href="#grammar-token-attribute_name"><tt class="xref docutils literal"><span class="pre">attribute_name</span></tt></a> | "[" <a class="reference internal" href="#grammar-token-element_index"><tt class="xref docutils literal"><span class="pre">element_index</span></tt></a> "]")*
- <strong id="grammar-token-arg_name">arg_name </strong> ::= [<a class="reference internal" href="../reference/lexical_analysis.html#grammar-token-identifier"><tt class="xref docutils literal"><span class="pre">identifier</span></tt></a> | <a class="reference internal" href="../reference/lexical_analysis.html#grammar-token-integer"><tt class="xref docutils literal"><span class="pre">integer</span></tt></a>]
- <strong id="grammar-token-attribute_name">attribute_name </strong> ::= <a class="reference internal" href="../reference/lexical_analysis.html#grammar-token-identifier"><tt class="xref docutils literal"><span class="pre">identifier</span></tt></a>
- <strong id="grammar-token-element_index">element_index </strong> ::= <a class="reference internal" href="../reference/lexical_analysis.html#grammar-token-integer"><tt class="xref docutils literal"><span class="pre">integer</span></tt></a> | <a class="reference internal" href="#grammar-token-index_string"><tt class="xref docutils literal"><span class="pre">index_string</span></tt></a>
- <strong id="grammar-token-index_string">index_string </strong> ::= <any source character except "]"> +
- <strong id="grammar-token-conversion">conversion </strong> ::= "r" | "s"
- <strong id="grammar-token-format_spec">format_spec </strong> ::= <described in the next section>
- </pre>
- </div></blockquote>
- <p>In less formal terms, the replacement field can start with a <em>field_name</em> that specifies
- the object whose value is to be formatted and inserted
- into the output instead of the replacement field.
- The <em>field_name</em> is optionally followed by a <em>conversion</em> field, which is
- preceded by an exclamation point <tt class="docutils literal"><span class="pre">'!'</span></tt>, and a <em>format_spec</em>, which is preceded
- by a colon <tt class="docutils literal"><span class="pre">':'</span></tt>. These specify a non-default format for the replacement value.</p>
- <p>See also the <a class="reference internal" href="#formatspec"><em>Format Specification Mini-Language</em></a> section.</p>
- <p>The <em>field_name</em> itself begins with an <em>arg_name</em> that is either a number or a
- keyword. If it’s a number, it refers to a positional argument, and if it’s a keyword,
- it refers to a named keyword argument. If the numerical arg_names in a format string
- are 0, 1, 2, ... in sequence, they can all be omitted (not just some)
- and the numbers 0, 1, 2, ... will be automatically inserted in that order.
- Because <em>arg_name</em> is not quote-delimited, it is not possible to specify arbitrary
- dictionary keys (e.g., the strings <tt class="docutils literal"><span class="pre">'10'</span></tt> or <tt class="docutils literal"><span class="pre">':-]'</span></tt>) within a format string.
- The <em>arg_name</em> can be followed by any number of index or
- attribute expressions. An expression of the form <tt class="docutils literal"><span class="pre">'.name'</span></tt> selects the named
- attribute using <a class="reference internal" href="functions.html#getattr" title="getattr"><tt class="xref py py-func docutils literal"><span class="pre">getattr()</span></tt></a>, while an expression of the form <tt class="docutils literal"><span class="pre">'[index]'</span></tt>
- does an index lookup using <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><tt class="xref py py-func docutils literal"><span class="pre">__getitem__()</span></tt></a>.</p>
- <p class="versionchanged">
- <span class="versionmodified">Changed in version 2.7: </span>The positional argument specifiers can be omitted, so <tt class="docutils literal"><span class="pre">'{}</span> <span class="pre">{}'</span></tt> is
- equivalent to <tt class="docutils literal"><span class="pre">'{0}</span> <span class="pre">{1}'</span></tt>.</p>
- <p>Some simple format string examples:</p>
- <div class="highlight-python"><div class="highlight"><pre><span class="s">"First, thou shalt count to {0}"</span> <span class="c"># References first positional argument</span>
- <span class="s">"Bring me a {}"</span> <span class="c"># Implicitly references the first positional argument</span>
- <span class="s">"From {} to {}"</span> <span class="c"># Same as "From {0} to {1}"</span>
- <span class="s">"My quest is {name}"</span> <span class="c"># References keyword argument 'name'</span>
- <span class="s">"Weight in tons {0.weight}"</span> <span class="c"># 'weight' attribute of first positional arg</span>
- <span class="s">"Units destroyed: {players[0]}"</span> <span class="c"># First element of keyword argument 'players'.</span>
- </pre></div>
- </div>
- <p>The <em>conversion</em> field causes a type coercion before formatting. Normally, the
- job of formatting a value is done by the <tt class="xref py py-meth docutils literal"><span class="pre">__format__()</span></tt> method of the value
- itself. However, in some cases it is desirable to force a type to be formatted
- as a string, overriding its own definition of formatting. By converting the
- value to a string before calling <tt class="xref py py-meth docutils literal"><span class="pre">__format__()</span></tt>, the normal formatting logic
- is bypassed.</p>
- <p>Two conversion flags are currently supported: <tt class="docutils literal"><span class="pre">'!s'</span></tt> which calls <a class="reference internal" href="functions.html#str" title="str"><tt class="xref py py-func docutils literal"><span class="pre">str()</span></tt></a>
- on the value, and <tt class="docutils literal"><span class="pre">'!r'</span></tt> which calls <a class="reference internal" href="repr.html#module-repr" title="repr: Alternate repr() implementation with size limits."><tt class="xref py py-func docutils literal"><span class="pre">repr()</span></tt></a>.</p>
- <p>Some examples:</p>
- <div class="highlight-python"><div class="highlight"><pre><span class="s">"Harold's a clever {0!s}"</span> <span class="c"># Calls str() on the argument first</span>
- <span class="s">"Bring out the holy {name!r}"</span> <span class="c"># Calls repr() on the argument first</span>
- </pre></div>
- </div>
- <p>The <em>format_spec</em> field contains a specification of how the value should be
- presented, including such details as field width, alignment, padding, decimal
- precision and so on. Each value type can define its own “formatting
- mini-language” or interpretation of the <em>format_spec</em>.</p>
- <p>Most built-in types support a common formatting mini-language, which is
- described in the next section.</p>
- <p>A <em>format_spec</em> field can also include nested replacement fields within it.
- These nested replacement fields can contain only a field name; conversion flags
- and format specifications are not allowed. The replacement fields within the
- format_spec are substituted before the <em>format_spec</em> string is interpreted.
- This allows the formatting of a value to be dynamically specified.</p>
- <p>See the <a class="reference internal" href="#formatexamples"><em>Format examples</em></a> section for some examples.</p>
- <div class="section" id="format-specification-mini-language">
- <span id="formatspec"></span><h3>7.1.3.1. Format Specification Mini-Language<a class="headerlink" href="#format-specification-mini-language" title="Permalink to this headline">¶</a></h3>
- <p>“Format specifications” are used within replacement fields contained within a
- format string to define how individual values are presented (see
- <a class="reference internal" href="#formatstrings"><em>Format String Syntax</em></a>). They can also be passed directly to the built-in
- <a class="reference internal" href="functions.html#format" title="format"><tt class="xref py py-func docutils literal"><span class="pre">format()</span></tt></a> function. Each formattable type may define how the format
- specification is to be interpreted.</p>
- <p>Most built-in types implement the following options for format specifications,
- although some of the formatting options are only supported by the numeric types.</p>
- <p>A general convention is that an empty format string (<tt class="docutils literal"><span class="pre">""</span></tt>) produces
- the same result as if you had called <a class="reference internal" href="functions.html#str" title="str"><tt class="xref py py-func docutils literal"><span class="pre">str()</span></tt></a> on the value. A
- non-empty format string typically modifies the result.</p>
- <p>The general form of a <em>standard format specifier</em> is:</p>
- <pre>
- <strong id="id1">format_spec</strong> ::= [[<a class="reference internal" href="#grammar-token-fill"><tt class="xref docutils literal"><span class="pre">fill</span></tt></a>]<a class="reference internal" href="#grammar-token-align"><tt class="xref docutils literal"><span class="pre">align</span></tt></a>][<a class="reference internal" href="#grammar-token-sign"><tt class="xref docutils literal"><span class="pre">sign</span></tt></a>][#][0][<a class="reference internal" href="#grammar-token-width"><tt class="xref docutils literal"><span class="pre">width</span></tt></a>][,][.<a class="reference internal" href="#grammar-token-precision"><tt class="xref docutils literal"><span class="pre">precision</span></tt></a>][<a class="reference internal" href="#grammar-token-type"><tt class="xref docutils literal"><span class="pre">type</span></tt></a>]
- <strong id="grammar-token-fill">fill </strong> ::= <a character other than '{' or '}'>
- <strong id="grammar-token-align">align </strong> ::= "<" | ">" | "=" | "^"
- <strong id="grammar-token-sign">sign </strong> ::= "+" | "-" | " "
- <strong id="grammar-token-width">width </strong> ::= <a class="reference internal" href="../reference/lexical_analysis.html#grammar-token-integer"><tt class="xref docutils literal"><span class="pre">integer</span></tt></a>
- <strong id="grammar-token-precision">precision </strong> ::= <a class="reference internal" href="../reference/lexical_analysis.html#grammar-token-integer"><tt class="xref docutils literal"><span class="pre">integer</span></tt></a>
- <strong id="grammar-token-type">type </strong> ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
- </pre>
- <p>The <em>fill</em> character can be any character other than ‘{‘ or ‘}’. The presence
- of a fill character is signaled by the character following it, which must be
- one of the alignment options. If the second character of <em>format_spec</em> is not
- a valid alignment option, then it is assumed that both the fill character and
- the alignment option are absent.</p>
- <p>The meaning of the various alignment options is as follows:</p>
- <blockquote>
- <div><table border="1" class="docutils">
- <colgroup>
- <col width="13%" />
- <col width="87%" />
- </colgroup>
- <thead valign="bottom">
- <tr><th class="head">Option</th>
- <th class="head">Meaning</th>
- </tr>
- </thead>
- <tbody valign="top">
- <tr><td><tt class="docutils literal"><span class="pre">'<'</span></tt></td>
- <td>Forces the field to be left-aligned within the available
- space (this is the default for most objects).</td>
- </tr>
- <tr><td><tt class="docutils literal"><span class="pre">'>'</span></tt></td>
- <td>Forces the field to be right-aligned within the
- available space (this is the default for numbers).</td>
- </tr>
- <tr><td><tt class="docutils literal"><span class="pre">'='</span></tt></td>
- <td>Forces the padding to be placed after the sign (if any)
- but before the digits. This is used for printing fields
- in the form ‘+000000120’. This alignment option is only
- valid for numeric types.</td>
- </tr>
- <tr><td><tt class="docutils literal"><span class="pre">'^'</span></tt></td>
- <td>Forces the field to be centered within the available
- space.</td>
- </tr>
- </tbody>
- </table>
- </div></blockquote>
- <p>Note that unless a minimum field width is defined, the field width will always
- be the same size as the data to fill it, so that the alignment option has no
- meaning in this case.</p>
- <p>The <em>sign</em> option is only valid for number types, and can be one of the
- following:</p>
- <blockquote>
- <div><table border="1" class="docutils">
- <colgroup>
- <col width="13%" />
- <col width="87%" />
- </colgroup>
- <thead valign="bottom">
- <tr><th class="head">Option</th>
- <th class="head">Meaning</th>
- </tr>
- </thead>
- <tbody valign="top">
- <tr><td><tt class="docutils literal"><span class="pre">'+'</span></tt></td>
- <td>indicates that a sign should be used for both
- positive as well as negative numbers.</td>
- </tr>
- <tr><td><tt class="docutils literal"><span class="pre">'-'</span></tt></td>
- <td>indicates that a sign should be used only for negative
- numbers (this is the default behavior).</td>
- </tr>
- <tr><td>space</td>
- <td>indicates that a leading space should be used on
- positive numbers, and a minus sign on negative numbers.</td>
- </tr>
- </tbody>
- </table>
- </div></blockquote>
- <p>The <tt class="docutils literal"><span class="pre">'#'</span></tt> option is only valid for integers, and only for binary, octal, or
- hexadecimal output. If present, it specifies that the output will be prefixed
- by <tt class="docutils literal"><span class="pre">'0b'</span></tt>, <tt class="docutils literal"><span class="pre">'0o'</span></tt>, or <tt class="docutils literal"><span class="pre">'0x'</span></tt>, respectively.</p>
- <p>The <tt class="docutils literal"><span class="pre">','</span></tt> option signals the use of a comma for a thousands separator.
- For a locale aware separator, use the <tt class="docutils literal"><span class="pre">'n'</span></tt> integer presentation type
- instead.</p>
- <p class="versionchanged">
- <span class="versionmodified">Changed in version 2.7: </span>Added the <tt class="docutils literal"><span class="pre">','</span></tt> option (see also <span class="target" id="index-3"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0378"><strong>PEP 378</strong></a>).</p>
- <p><em>width</em> is a decimal integer defining the minimum field width. If not
- specified, then the field width will be determined by the content.</p>
- <p>Preceding the <em>width</em> field by a zero (<tt class="docutils literal"><span class="pre">'0'</span></tt>) character enables
- sign-aware zero-padding for numeric types. This is equivalent to a <em>fill</em>
- character of <tt class="docutils literal"><span class="pre">'0'</span></tt> with an <em>alignment</em> type of <tt class="docutils literal"><span class="pre">'='</span></tt>.</p>
- <p>The <em>precision</em> is a decimal number indicating how many digits should be
- displayed after the decimal point for a floating point value formatted with
- <tt class="docutils literal"><span class="pre">'f'</span></tt> and <tt class="docutils literal"><span class="pre">'F'</span></tt>, or before and after the decimal point for a floating point
- value formatted with <tt class="docutils literal"><span class="pre">'g'</span></tt> or <tt class="docutils literal"><span class="pre">'G'</span></tt>. For non-number types the field
- indicates the maximum field size - in other words, how many characters will be
- used from the field content. The <em>precision</em> is not allowed for integer values.</p>
- <p>Finally, the <em>type</em> determines how the data should be presented.</p>
- <p>The available string presentation types are:</p>
- <blockquote>
- <div><table border="1" class="docutils">
- <colgroup>
- <col width="13%" />
- <col width="87%" />
- </colgroup>
- <thead valign="bottom">
- <tr><th class="head">Type</th>
- <th class="head">Meaning</th>
- </tr>
- </thead>
- <tbody valign="top">
- <tr><td><tt class="docutils literal"><span class="pre">'s'</span></tt></td>
- <td>String format. This is the default type for strings and
- may be omitted.</td>
- </tr>
- <tr><td>None</td>
- <td>The same as <tt class="docutils literal"><span class="pre">'s'</span></tt>.</td>
- </tr>
- </tbody>
- </table>
- </div></blockquote>
- <p>The available integer presentation types are:</p>
- <blockquote>
- <div><table border="1" class="docutils">
- <colgroup>
- <col width="13%" />
- <col width="87%" />
- </colgroup>
- <thead valign="bottom">
- <tr><th class="head">Type</th>
- <th class="head">Meaning</th>
- </tr>
- </thead>
- <tbody valign="top">
- <tr><td><tt class="docutils literal"><span class="pre">'b'</span></tt></td>
- <td>Binary format. Outputs the number in base 2.</td>
- </tr>
- <tr><td><tt class="docutils literal"><span class="pre">'c'</span></tt></td>
- <td>Character. Converts the integer to the corresponding
- unicode character before printing.</td>
- </tr>
- <tr><td><tt class="docutils literal"><span class="pre">'d'</span></tt></td>
- <td>Decimal Integer. Outputs the number in base 10.</td>
- </tr>
- <tr><td><tt class="docutils literal"><span class="pre">'o'</span></tt></td>
- <td>Octal format. Outputs the number in base 8.</td>
- </tr>
- <tr><td><tt class="docutils literal"><span class="pre">'x'</span></tt></td>
- <td>Hex format. Outputs the number in base 16, using lower-
- case letters for the digits above 9.</td>
- </tr>
- <tr><td><tt class="docutils literal"><span class="pre">'X'</span></tt></td>
- <td>Hex format. Outputs the number in base 16, using upper-
- case letters for the digits above 9.</td>
- </tr>
- <tr><td><tt class="docutils literal"><span class="pre">'n'</span></tt></td>
- <td>Number. This is the same as <tt class="docutils literal"><span class="pre">'d'</span></tt>, except that it uses
- the current locale setting to insert the appropriate
- number separator characters.</td>
- </tr>
- <tr><td>None</td>
- <td>The same as <tt class="docutils literal"><span class="pre">'d'</span></tt>.</td>
- </tr>
- </tbody>
- </table>
- </div></blockquote>
- <p>In addition to the above presentation types, integers can be formatted
- with the floating point presentation types listed below (except
- <tt class="docutils literal"><span class="pre">'n'</span></tt> and None). When doing so, <a class="reference internal" href="functions.html#float" title="float"><tt class="xref py py-func docutils literal"><span class="pre">float()</span></tt></a> is used to convert the
- integer to a floating point number before formatting.</p>
- <p>The available presentation types for floating point and decimal values are:</p>
- <blockquote>
- <div><table border="1" class="docutils">
- <colgroup>
- <col width="13%" />
- <col width="87%" />
- </colgroup>
- <thead valign="bottom">
- <tr><th class="head">Type</th>
- <th class="head">Meaning</th>
- </tr>
- </thead>
- <tbody valign="top">
- <tr><td><tt class="docutils literal"><span class="pre">'e'</span></tt></td>
- <td>Exponent notation. Prints the number in scientific
- notation using the letter ‘e’ to indicate the exponent.</td>
- </tr>
- <tr><td><tt class="docutils literal"><span class="pre">'E'</span></tt></td>
- <td>Exponent notation. Same as <tt class="docutils literal"><span class="pre">'e'</span></tt> except it uses an
- upper case ‘E’ as the separator character.</td>
- </tr>
- <tr><td><tt class="docutils literal"><span class="pre">'f'</span></tt></td>
- <td>Fixed point. Displays the number as a fixed-point
- number.</td>
- </tr>
- <tr><td><tt class="docutils literal"><span class="pre">'F'</span></tt></td>
- <td>Fixed point. Same as <tt class="docutils literal"><span class="pre">'f'</span></tt>.</td>
- </tr>
- <tr><td><tt class="docutils literal"><span class="pre">'g'</span></tt></td>
- <td><p class="first">General format. For a given precision <tt class="docutils literal"><span class="pre">p</span> <span class="pre">>=</span> <span class="pre">1</span></tt>,
- this rounds the number to <tt class="docutils literal"><span class="pre">p</span></tt> significant digits and
- then formats the result in either fixed-point format
- or in scientific notation, depending on its magnitude.</p>
- <p>The precise rules are as follows: suppose that the
- result formatted with presentation type <tt class="docutils literal"><span class="pre">'e'</span></tt> and
- precision <tt class="docutils literal"><span class="pre">p-1</span></tt> would have exponent <tt class="docutils literal"><span class="pre">exp</span></tt>. Then
- if <tt class="docutils literal"><span class="pre">-4</span> <span class="pre"><=</span> <span class="pre">exp</span> <span class="pre"><</span> <span class="pre">p</span></tt>, the number is formatted
- with presentation type <tt class="docutils literal"><span class="pre">'f'</span></tt> and precision
- <tt class="docutils literal"><span class="pre">p-1-exp</span></tt>. Otherwise, the number is formatted
- with presentation type <tt class="docutils literal"><span class="pre">'e'</span></tt> and precision <tt class="docutils literal"><span class="pre">p-1</span></tt>.
- In both cases insignificant trailing zeros are removed
- from the significand, and the decimal point is also
- removed if there are no remaining digits following it.</p>
- <p>Positive and negative infinity, positive and negative
- zero, and nans, are formatted as <tt class="docutils literal"><span class="pre">inf</span></tt>, <tt class="docutils literal"><span class="pre">-inf</span></tt>,
- <tt class="docutils literal"><span class="pre">0</span></tt>, <tt class="docutils literal"><span class="pre">-0</span></tt> and <tt class="docutils literal"><span class="pre">nan</span></tt> respectively, regardless of
- the precision.</p>
- <p class="last">A precision of <tt class="docutils literal"><span class="pre">0</span></tt> is treated as equivalent to a
- precision of <tt class="docutils literal"><span class="pre">1</span></tt>.</p>
- </td>
- </tr>
- <tr><td><tt class="docutils literal"><span class="pre">'G'</span></tt></td>
- <td>General format. Same as <tt class="docutils literal"><span class="pre">'g'</span></tt> except switches to
- <tt class="docutils literal"><span class="pre">'E'</span></tt> if the number gets too large. The
- representations of infinity and NaN are uppercased, too.</td>
- </tr>
- <tr><td><tt class="docutils literal"><span class="pre">'n'</span></tt></td>
- <td>Number. This is the same as <tt class="docutils literal"><span class="pre">'g'</span></tt>, except that it uses
- the current locale setting to insert the appropriate
- number separator characters.</td>
- </tr>
- <tr><td><tt class="docutils literal"><span class="pre">'%'</span></tt></td>
- <td>Percentage. Multiplies the number by 100 and displays
- in fixed (<tt class="docutils literal"><span class="pre">'f'</span></tt>) format, followed by a percent sign.</td>
- </tr>
- <tr><td>None</td>
- <td>The same as <tt class="docutils literal"><span class="pre">'g'</span></tt>.</td>
- </tr>
- </tbody>
- </table>
- </div></blockquote>
- </div>
- <div class="section" id="format-examples">
- <span id="formatexamples"></span><h3>7.1.3.2. Format examples<a class="headerlink" href="#format-examples" title="Permalink to this headline">¶</a></h3>
- <p>This section contains examples of the new format syntax and comparison with
- the old <tt class="docutils literal"><span class="pre">%</span></tt>-formatting.</p>
- <p>In most of the cases the syntax is similar to the old <tt class="docutils literal"><span class="pre">%</span></tt>-formatting, with the
- addition of the <tt class="docutils literal"><span class="pre">{}</span></tt> and with <tt class="docutils literal"><span class="pre">:</span></tt> used instead of <tt class="docutils literal"><span class="pre">%</span></tt>.
- For example, <tt class="docutils literal"><span class="pre">'%03.2f'</span></tt> can be translated to <tt class="docutils literal"><span class="pre">'{:03.2f}'</span></tt>.</p>
- <p>The new format syntax also supports new and different options, shown in the
- follow examples.</p>
- <p>Accessing arguments by position:</p>
- <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span