@@ -27,16 +27,16 @@ 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.
31+
32+ The :mod: ` string ` module contains a class Template which offers yet another way
33+ to substitute values into strings .
3434
3535One question remains, of course: how do you convert values to strings? Luckily,
3636Python has ways to convert any value to a string: pass it to the :func: `repr `
3737or :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.
38+ :func: `repr `, but they are no longer used in modern Python code and are removed
39+ in future versions of the language.
4040
4141The :func: `str ` function is meant to return representations of values which are
4242fairly human-readable, while :func: `repr ` is meant to generate representations
@@ -94,7 +94,7 @@ Here are two ways to write a table of squares and cubes::
9494 10 100 1000
9595
9696 >>> for x in range(1, 11):
97- ... print('%2d %3d %4d' % (x, x*x, x*x*x))
97+ ... print('{0:2d} {1:3d} {2:4d}'.format (x, x*x, x*x*x))
9898 ...
9999 1 1 1
100100 2 4 8
@@ -129,44 +129,91 @@ with zeros. It understands about plus and minus signs::
129129 >>> '3.14159265359'.zfill(5)
130130 '3.14159265359'
131131
132- Using the ``% `` operator looks like this::
132+ Basic usage of the :meth: `str.format ` method looks like this::
133+
134+ >>> print 'We are the {0} who say "{1}!"'.format('knights', 'Ni')
135+ We are the knights who say "Ni!"
136+
137+ The brackets and characters within them (called format fields) are replaced with
138+ the objects passed into the format method. The number in the brackets refers to
139+ the position of the object passed into the format method. ::
140+
141+ >>> print '{0} and {1}'.format('spam', 'eggs')
142+ spam and eggs
143+ >>> print '{1} and {0}'.format('spam', 'eggs')
144+ eggs and spam
145+
146+ If keyword arguments are used in the format method, their values are referred to
147+ by using the name of the argument. ::
148+
149+ >>> print 'This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible')
150+ This spam is absolutely horrible.
151+
152+ Positional and keyword arguments can be arbitrarily combined::
153+
154+ >>> print 'The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Georg')
155+ The story of Bill, Manfred, and Georg.
156+
157+ An optional ``':` `` and format specifier can follow the field name. This also
158+ greater control over how the value is formatted. The following example
159+ truncates the Pi to three places after the decimal.
133160
134161 >>> import math
135- >>> print('The value of PI is approximately %5 .3f.' % math.pi)
162+ >>> print (' The value of PI is approximately {0 : .3f} . ' .format( math.pi) )
136163 The value of PI is approximately 3.142.
137164
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 ::
165+ Passing an integer after the `` ':' `` will cause that field to be a minimum
166+ number of characters wide. This is useful for making tables pretty. ::
140167
141168 >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
142169 >>> for name, phone in table.items():
143- ... print('%-10s ==> % 10d' % (name, phone))
170+ ... print('{0:10} ==> {1: 10d}'.format (name, phone))
144171 ...
145172 Jack ==> 4098
146173 Dcab ==> 7678
147174 Sjoerd ==> 4127
148175
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-
156176If you have a really long format string that you don't want to split up, it
157177would 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 ::
178+ instead of by position. This can be done by simply passing the dict and using
179+ square brackets `` '[]' `` to access the keys ::
160180
161181 >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
162- >>> print('Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table)
182+ >>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; Dcab: {0[Dcab]:d}'.format(table))
183+ Jack: 4098; Sjoerd: 4127; Dcab: 8637678
184+
185+ This could also be done by passing the table as keyword arguments with the '**'
186+ notation.::
187+
188+ >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
189+ >>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
163190 Jack: 4098; Sjoerd: 4127; Dcab: 8637678
164191
165192This is particularly useful in combination with the new built-in :func: `vars `
166193function, which returns a dictionary containing all local variables.
167194
168- The :mod: `string ` module contains a class Template which offers yet another way
169- to substitute values into strings.
195+ For a complete overview of string formating with :meth: `str.format `, see
196+ :ref: `formatstrings `.
197+
198+
199+ Old string formatting
200+ ---------------------
201+
202+ The ``% `` operator can also be used for string formatting. It interprets the
203+ left argument much like a :cfunc: `sprintf `\ -style format string to be applied
204+ to the right argument, and returns the string resulting from this formatting
205+ operation. For example::
206+
207+ >>> import math
208+ >>> print 'The value of PI is approximately %5.3f.' % math.pi
209+ The value of PI is approximately 3.142.
210+
211+ Since :meth: `str.format ` is quite new, a lot of Python code still uses the ``% ``
212+ operator. However, because this old style of formatting will eventually removed
213+ from the language :meth: `str.format ` should generally be used.
214+
215+ More information can be found in the :ref: `old-string-formatting ` section.
216+
170217
171218.. _tut-files :
172219
0 commit comments