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

Skip to content

Commit f9ef988

Browse files
committed
update the tutorial to use str.format
1 parent c15205e commit f9ef988

7 files changed

Lines changed: 81 additions & 32 deletions

File tree

Doc/tutorial/controlflow.rst

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

448-
def fprintf(file, format, *args):
449-
file.write(format % args)
448+
def fprintf(file, template, *args):
449+
file.write(template.format(args))
450450

451451

452452
.. _tut-unpacking-arguments:

Doc/tutorial/datastructures.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -550,7 +550,7 @@ with the :func:`zip` function. ::
550550
>>> questions = ['name', 'quest', 'favorite color']
551551
>>> answers = ['lancelot', 'the holy grail', 'blue']
552552
>>> for q, a in zip(questions, answers):
553-
... print 'What is your %s? It is %s.' % (q, a)
553+
... print 'What is your {0}? It is {1}.'.format(q, a)
554554
...
555555
What is your name? It is lancelot.
556556
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

140139
.. _tut-fp-error:

Doc/tutorial/inputoutput.rst

Lines changed: 68 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -27,16 +27,13 @@ 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.
3431

3532
One question remains, of course: how do you convert values to strings? Luckily,
3633
Python has ways to convert any value to a string: pass it to the :func:`repr`
3734
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.
35+
:func:`repr`, but they are no longer used in modern Python code and are removed
36+
in future versions of the language.
4037

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

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

Doc/tutorial/introduction.rst

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -372,9 +372,13 @@ The built-in function :func:`len` returns the length of a string::
372372
Both strings and Unicode strings support a large number of methods for
373373
basic transformations and searching.
374374

375+
:ref:`new-string-formatting`
376+
Information about string formatting with :meth:`str.format` is described
377+
here.
378+
375379
:ref:`string-formatting`
376-
The formatting operations invoked when strings and Unicode strings are the
377-
left operand of the ``%`` operator are described in more detail here.
380+
The old formatting operations invoked when strings and Unicode strings are
381+
the left operand of the ``%`` operator are described in more detail here.
378382

379383

380384
.. _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)