Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e6f0063

Browse files
committed
Merged revisions 63655 via svnmerge from
svn+ssh://[email protected]/python/trunk ........ r63655 | benjamin.peterson | 2008-05-25 19:54:22 -0500 (Sun, 25 May 2008) | 2 lines update the tutorial to use str.format ........
1 parent dc6c16a commit e6f0063

7 files changed

Lines changed: 84 additions & 34 deletions

File tree

Doc/tutorial/controlflow.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -475,8 +475,8 @@ called with an arbitrary number of arguments. These arguments will be wrapped
475475
up in a tuple. Before the variable number of arguments, zero or more normal
476476
arguments may occur. ::
477477

478-
def fprintf(file, format, *args):
479-
file.write(format % args)
478+
def fprintf(file, template, *args):
479+
file.write(template.format(args))
480480

481481
482482
Normally, these ``variadic`` arguments will be last in the list of formal

Doc/tutorial/datastructures.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -515,7 +515,7 @@ with the :func:`zip` function. ::
515515
>>> questions = ['name', 'quest', 'favorite color']
516516
>>> answers = ['lancelot', 'the holy grail', 'blue']
517517
>>> for q, a in zip(questions, answers):
518-
... print('What is your %s? It is %s.' % (q, a))
518+
... print('What is your {0}? It is {1}.'.format(q, a))
519519
...
520520
What is your name? It is lancelot.
521521
What is your quest? It is the holy grail.

Doc/tutorial/errors.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ the exception (allowing a caller to handle the exception as well)::
132132
s = f.readline()
133133
i = int(s.strip())
134134
except IOError as (errno, strerror):
135-
print("I/O error(%s): %s" % (errno, strerror))
135+
print("I/O error({0}): {1}".format(errno, strerror))
136136
except ValueError:
137137
print("Could not convert data to an integer.")
138138
except:

Doc/tutorial/floatingpoint.rst

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -132,9 +132,8 @@ that every float operation can suffer a new rounding error.
132132
While pathological cases do exist, for most casual use of floating-point
133133
arithmetic you'll see the result you expect in the end if you simply round the
134134
display of your final results to the number of decimal digits you expect.
135-
:func:`str` usually suffices, and for finer control see the discussion of
136-
Python's ``%`` format operator: the ``%g``, ``%f`` and ``%e`` format codes
137-
supply flexible and easy ways to round float results for display.
135+
:func:`str` usually suffices, and for finer control see the :meth:`str.format`
136+
method's format specifiers in :ref:`formatstrings`.
138137

139138
If you are a heavy user of floating point operations you should take a look
140139
at the Numerical Python package and many other packages for mathematical and

Doc/tutorial/inputoutput.rst

Lines changed: 71 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -27,16 +27,16 @@ first way is to do all the string handling yourself; using string slicing and
2727
concatenation operations you can create any layout you can imagine. The
2828
standard module :mod:`string` contains some useful operations for padding
2929
strings 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

3535
One question remains, of course: how do you convert values to strings? Luckily,
3636
Python has ways to convert any value to a string: pass it to the :func:`repr`
3737
or :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

4141
The :func:`str` function is meant to return representations of values which are
4242
fairly 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-
156176
If you have a really long format string that you don't want to split up, it
157177
would 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

165192
This is particularly useful in combination with the new built-in :func:`vars`
166193
function, 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

Doc/tutorial/introduction.rst

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -393,8 +393,12 @@ The built-in function :func:`len` returns the length of a string::
393393
basic transformations and searching.
394394

395395
:ref:`string-formatting`
396-
The formatting operations invoked by the :meth:`format` string method are
397-
described in more detail here.
396+
Information about string formatting with :meth:`str.format` is described
397+
here.
398+
399+
:ref:`old-string-formatting`
400+
The old formatting operations invoked when strings and Unicode strings are
401+
the left operand of the ``%`` operator are described in more detail here.
398402

399403

400404
.. _tut-unicodestrings:

Doc/tutorial/stdlib2.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ placeholders such as the current date, image sequence number, or file format::
116116
>>> for i, filename in enumerate(photofiles):
117117
... base, ext = os.path.splitext(filename)
118118
... newname = t.substitute(d=date, n=i, f=ext)
119-
... print('%s --> %s' % (filename, newname))
119+
... print('{0} --> {1}'.format(filename, newname))
120120

121121
img_1074.jpg --> Ashley_0.jpg
122122
img_1076.jpg --> Ashley_1.jpg

0 commit comments

Comments
 (0)