@@ -27,16 +27,13 @@ first way is to do all the string handling yourself; using string slicing and
2727concatenation operations you can create any layout you can imagine. The
2828standard module :mod: `string ` contains some useful operations for padding
2929strings to a given column width; these will be discussed shortly. The second
30- way is to use the ``% `` operator with a string as the left argument. The ``% ``
31- operator interprets the left argument much like a :cfunc: `sprintf `\ -style
32- format string to be applied to the right argument, and returns the string
33- resulting from this formatting operation.
30+ way is to use the :meth: `str.format ` method.
3431
3532One question remains, of course: how do you convert values to strings? Luckily,
3633Python has ways to convert any value to a string: pass it to the :func: `repr `
3734or :func: `str ` functions. Reverse quotes (```` ``) are equivalent to
38- :func: `repr `, but they are no longer used in modern Python code and will likely
39- not be in future versions of the language.
35+ :func: `repr `, but they are no longer used in modern Python code and are removed
36+ in future versions of the language.
4037
4138The :func: `str ` function is meant to return representations of values which are
4239fairly human-readable, while :func: `repr ` is meant to generate representations
@@ -94,7 +91,7 @@ Here are two ways to write a table of squares and cubes::
9491 10 100 1000
9592
9693 >>> for x in range(1,11):
97- ... print '%2d %3d %4d' % (x, x*x, x*x*x)
94+ ... print '{0:2d} {1:3d} {2:4d}'.format (x, x*x, x*x*x)
9895 ...
9996 1 1 1
10097 2 4 8
@@ -129,42 +126,91 @@ with zeros. It understands about plus and minus signs::
129126 >>> '3.14159265359'.zfill(5)
130127 '3.14159265359'
131128
132- Using the ``% `` operator looks like this::
129+ Basic usage of the :meth: `str.format ` method looks like this::
130+
131+ >>> print 'We are the {0} who say "{1}!"'.format('knights', 'Ni')
132+ We are the knights who say "Ni!"
133+
134+ The brackets and characters within them (called format fields) are replaced with
135+ the objects passed into the format method. The number in the brackets refers to
136+ the position of the object passed into the format method. ::
137+
138+ >>> print '{0} and {1}'.format('spam', 'eggs')
139+ spam and eggs
140+ >>> print '{1} and {0}'.format('spam', 'eggs')
141+ eggs and spam
142+
143+ If keyword arguments are used in the format method, their values are referred to
144+ by using the name of the argument. ::
145+
146+ >>> print 'This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible')
147+ This spam is absolutely horrible.
148+
149+ Positional and keyword arguments can be arbitrarily combined::
150+
151+ >>> print 'The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Georg')
152+ The story of Bill, Manfred, and Georg.
153+
154+ An optional ``':` `` and format specifier can follow the field name. This also
155+ greater control over how the value is formatted. The following example
156+ truncates the Pi to three places after the decimal.
133157
134158 >>> import math
135- >>> print 'The value of PI is approximately %5 .3f.' % math.pi
159+ >>> print ' The value of PI is approximately {0 : .3f} . ' .format( math.pi)
136160 The value of PI is approximately 3.142.
137161
138- If there is more than one format in the string, you need to pass a tuple as
139- right operand, as in this example ::
162+ Passing an integer after the `` ':' `` will cause that field to be a minimum
163+ number of characters wide. This is useful for making tables pretty. ::
140164
141165 >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
142166 >>> for name, phone in table.items():
143- ... print '%-10s ==> % 10d' % (name, phone)
167+ ... print '{0:10} ==> {1: 10d}'.format (name, phone)
144168 ...
145169 Jack ==> 4098
146170 Dcab ==> 7678
147171 Sjoerd ==> 4127
148172
149- Most formats work exactly as in C and require that you pass the proper type;
150- however, if you don't you get an exception, not a core dump. The ``%s `` format
151- is more relaxed: if the corresponding argument is not a string object, it is
152- converted to string using the :func: `str ` built-in function. Using ``* `` to
153- pass the width or precision in as a separate (integer) argument is supported.
154- The C formats ``%n `` and ``%p `` are not supported.
155-
156173If you have a really long format string that you don't want to split up, it
157174would be nice if you could reference the variables to be formatted by name
158- instead of by position. This can be done by using form ``%(name)format ``, as
159- shown here::
175+ instead of by position. This can be done by simply passing the dict and using
176+ square brackets ``'[]' `` to access the keys ::
177+
178+ >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
179+ >>> print 'Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; Dcab: {0[Dcab]:d}'.format(table)
180+ Jack: 4098; Sjoerd: 4127; Dcab: 8637678
181+
182+ This could also be done by passing the table as keyword arguments with the '**'
183+ notation.::
160184
161185 >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
162- >>> print 'Jack: %( Jack)d ; Sjoerd: %( Sjoerd)d ; Dcab: %( Dcab)d' % table
186+ >>> print 'Jack: { Jack:d} ; Sjoerd: { Sjoerd:d} ; Dcab: { Dcab:d}'.format(** table)
163187 Jack: 4098; Sjoerd: 4127; Dcab: 8637678
164188
165189This is particularly useful in combination with the new built-in :func: `vars `
166190function, which returns a dictionary containing all local variables.
167191
192+ For a complete overview of string formating with :meth: `str.format `, see
193+ :ref: `formatstrings `.
194+
195+
196+ Old string formatting
197+ ---------------------
198+
199+ The ``% `` operator can also be used for string formatting. It interprets the
200+ left argument much like a :cfunc: `sprintf `\ -style format string to be applied
201+ to the right argument, and returns the string resulting from this formatting
202+ operation. For example::
203+
204+ >>> import math
205+ >>> print 'The value of PI is approximately %5.3f.' % math.pi
206+ The value of PI is approximately 3.142.
207+
208+ Since :meth: `str.format ` is quite new, a lot of Python code still uses the ``% ``
209+ operator. However, because this old style of formatting will eventually removed
210+ from the language :meth: `str.format ` should generally be used.
211+
212+ More information can be found in the :ref: `string-formatting ` section.
213+
168214
169215.. _tut-files :
170216
0 commit comments