Commit 6911e3ce authored by Georg Brandl's avatar Georg Brandl

Convert all print statements in the docs.

parent c9879246
...@@ -143,8 +143,8 @@ Object Protocol ...@@ -143,8 +143,8 @@ Object Protocol
Compute a string representation of object *o*. Returns the string Compute a string representation of object *o*. Returns the string
representation on success, *NULL* on failure. This is the equivalent of the representation on success, *NULL* on failure. This is the equivalent of the
Python expression ``str(o)``. Called by the :func:`str` built-in function and Python expression ``str(o)``. Called by the :func:`str` built-in function
by the :keyword:`print` statement. and, therefore, by the :func:`print` function.
.. cfunction:: PyObject* PyObject_Unicode(PyObject *o) .. cfunction:: PyObject* PyObject_Unicode(PyObject *o)
......
...@@ -645,8 +645,8 @@ type objects) *must* have the :attr:`ob_size` field. ...@@ -645,8 +645,8 @@ type objects) *must* have the :attr:`ob_size` field.
The signature is the same as for :cfunc:`PyObject_Str`; it must return a string The signature is the same as for :cfunc:`PyObject_Str`; it must return a string
or a Unicode object. This function should return a "friendly" string or a Unicode object. This function should return a "friendly" string
representation of the object, as this is the representation that will be used by representation of the object, as this is the representation that will be used,
the print statement. among other things, by the :func:`print` function.
When this field is not set, :cfunc:`PyObject_Repr` is called to return a string When this field is not set, :cfunc:`PyObject_Repr` is called to return a string
representation. representation.
......
...@@ -64,7 +64,7 @@ perform some operation on a file. :: ...@@ -64,7 +64,7 @@ perform some operation on a file. ::
{ {
Py_Initialize(); Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n" PyRun_SimpleString("from time import time,ctime\n"
"print 'Today is',ctime(time())\n"); "print('Today is', ctime(time()))\n");
Py_Finalize(); Py_Finalize();
return 0; return 0;
} }
...@@ -141,7 +141,7 @@ array. If you compile and link this program (let's call the finished executable ...@@ -141,7 +141,7 @@ array. If you compile and link this program (let's call the finished executable
:program:`call`), and use it to execute a Python script, such as:: :program:`call`), and use it to execute a Python script, such as::
def multiply(a,b): def multiply(a,b):
print "Will compute", a, "times", b print("Will compute", a, "times", b)
c = 0 c = 0
for i in range(0, a): for i in range(0, a):
c = c + b c = c + b
...@@ -234,7 +234,7 @@ These two lines initialize the ``numargs`` variable, and make the ...@@ -234,7 +234,7 @@ These two lines initialize the ``numargs`` variable, and make the
With these extensions, the Python script can do things like :: With these extensions, the Python script can do things like ::
import emb import emb
print "Number of arguments", emb.numargs() print("Number of arguments", emb.numargs())
In a real application, the methods will expose an API of the application to In a real application, the methods will expose an API of the application to
Python. Python.
......
...@@ -826,11 +826,11 @@ increases an internal counter. :: ...@@ -826,11 +826,11 @@ increases an internal counter. ::
>>> import shoddy >>> import shoddy
>>> s = shoddy.Shoddy(range(3)) >>> s = shoddy.Shoddy(range(3))
>>> s.extend(s) >>> s.extend(s)
>>> print len(s) >>> print(len(s))
6 6
>>> print s.increment() >>> print(s.increment())
1 1
>>> print s.increment() >>> print(s.increment())
2 2
.. literalinclude:: ../includes/shoddy.c .. literalinclude:: ../includes/shoddy.c
...@@ -1063,34 +1063,6 @@ Here is a simple example:: ...@@ -1063,34 +1063,6 @@ Here is a simple example::
obj->obj_UnderlyingDatatypePtr->size); obj->obj_UnderlyingDatatypePtr->size);
} }
The print function will be called whenever Python needs to "print" an instance
of the type. For example, if 'node' is an instance of type TreeNode, then the
print function is called when Python code calls::
print node
There is a flags argument and one flag, :const:`Py_PRINT_RAW`, and it suggests
that you print without string quotes and possibly without interpreting escape
sequences.
The print function receives a file object as an argument. You will likely want
to write to that file object.
Here is a sample print function::
static int
newdatatype_print(newdatatypeobject *obj, FILE *fp, int flags)
{
if (flags & Py_PRINT_RAW) {
fprintf(fp, "<{newdatatype object--size: %d}>",
obj->obj_UnderlyingDatatypePtr->size);
}
else {
fprintf(fp, "\"<{newdatatype object--size: %d}>\"",
obj->obj_UnderlyingDatatypePtr->size);
}
return 0;
}
Attribute Management Attribute Management
......
...@@ -59,7 +59,7 @@ its least useful properties. ...@@ -59,7 +59,7 @@ its least useful properties.
Remember, you can never know for sure what names a module exports, so either Remember, you can never know for sure what names a module exports, so either
take what you need --- ``from module import name1, name2``, or keep them in the take what you need --- ``from module import name1, name2``, or keep them in the
module and access on a per-need basis --- ``import module;print module.name``. module and access on a per-need basis --- ``import module; print(module.name)``.
When It Is Just Fine When It Is Just Fine
...@@ -181,7 +181,7 @@ The following is a very popular anti-idiom :: ...@@ -181,7 +181,7 @@ The following is a very popular anti-idiom ::
def get_status(file): def get_status(file):
if not os.path.exists(file): if not os.path.exists(file):
print "file not found" print("file not found")
sys.exit(1) sys.exit(1)
return open(file).readline() return open(file).readline()
...@@ -199,7 +199,7 @@ Here is a better way to do it. :: ...@@ -199,7 +199,7 @@ Here is a better way to do it. ::
try: try:
return open(file).readline() return open(file).readline()
except (IOError, OSError): except (IOError, OSError):
print "file not found" print("file not found")
sys.exit(1) sys.exit(1)
In this version, \*either\* the file gets opened and the line is read (so it In this version, \*either\* the file gets opened and the line is read (so it
...@@ -264,12 +264,13 @@ More useful functions in :mod:`os.path`: :func:`basename`, :func:`dirname` and ...@@ -264,12 +264,13 @@ More useful functions in :mod:`os.path`: :func:`basename`, :func:`dirname` and
There are also many useful builtin functions people seem not to be aware of for There are also many useful builtin functions people seem not to be aware of for
some reason: :func:`min` and :func:`max` can find the minimum/maximum of any some reason: :func:`min` and :func:`max` can find the minimum/maximum of any
sequence with comparable semantics, for example, yet many people write their own sequence with comparable semantics, for example, yet many people write their own
:func:`max`/:func:`min`. Another highly useful function is :func:`reduce`. A :func:`max`/:func:`min`. Another highly useful function is
classical use of :func:`reduce` is something like :: :func:`functools.reduce`. A classical use of :func:`reduce` is something like
::
import sys, operator import sys, operator, functools
nums = map(float, sys.argv[1:]) nums = map(float, sys.argv[1:])
print reduce(operator.add, nums)/len(nums) print(functools.reduce(operator.add, nums) / len(nums))
This cute little script prints the average of all numbers given on the command This cute little script prints the average of all numbers given on the command
line. The :func:`reduce` adds up all the numbers, and the rest is just some line. The :func:`reduce` adds up all the numbers, and the rest is just some
......
...@@ -201,7 +201,7 @@ You can experiment with the iteration interface manually:: ...@@ -201,7 +201,7 @@ You can experiment with the iteration interface manually::
>>> L = [1,2,3] >>> L = [1,2,3]
>>> it = iter(L) >>> it = iter(L)
>>> print it >>> it
<iterator object at 0x8116870> <iterator object at 0x8116870>
>>> it.next() >>> it.next()
1 1
...@@ -221,10 +221,10 @@ be an iterator or some object for which ``iter()`` can create an iterator. ...@@ -221,10 +221,10 @@ be an iterator or some object for which ``iter()`` can create an iterator.
These two statements are equivalent:: These two statements are equivalent::
for i in iter(obj): for i in iter(obj):
print i print(i)
for i in obj: for i in obj:
print i print(i)
Iterators can be materialized as lists or tuples by using the :func:`list` or Iterators can be materialized as lists or tuples by using the :func:`list` or
:func:`tuple` constructor functions:: :func:`tuple` constructor functions::
...@@ -274,7 +274,7 @@ dictionary's keys:: ...@@ -274,7 +274,7 @@ dictionary's keys::
>>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6, >>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
... 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12} ... 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
>>> for key in m: >>> for key in m:
... print key, m[key] ... print(key, m[key])
Mar 3 Mar 3
Feb 2 Feb 2
Aug 8 Aug 8
...@@ -316,7 +316,7 @@ elements:: ...@@ -316,7 +316,7 @@ elements::
S = set((2, 3, 5, 7, 11, 13)) S = set((2, 3, 5, 7, 11, 13))
for i in S: for i in S:
print i print(i)
...@@ -568,18 +568,18 @@ the internal counter. ...@@ -568,18 +568,18 @@ the internal counter.
And here's an example of changing the counter: And here's an example of changing the counter:
>>> it = counter(10) >>> it = counter(10)
>>> print it.next() >>> it.next()
0 0
>>> print it.next() >>> it.next()
1 1
>>> print it.send(8) >>> it.send(8)
8 8
>>> print it.next() >>> it.next()
9 9
>>> print it.next() >>> it.next()
Traceback (most recent call last): Traceback (most recent call last):
File ``t.py'', line 15, in ? File ``t.py'', line 15, in ?
print it.next() it.next()
StopIteration StopIteration
Because ``yield`` will often be returning ``None``, you should always check for Because ``yield`` will often be returning ``None``, you should always check for
...@@ -721,7 +721,7 @@ indexes at which certain conditions are met:: ...@@ -721,7 +721,7 @@ indexes at which certain conditions are met::
f = open('data.txt', 'r') f = open('data.txt', 'r')
for i, line in enumerate(f): for i, line in enumerate(f):
if line.strip() == '': if line.strip() == '':
print 'Blank line at line #%i' % i print('Blank line at line #%i' % i)
``sorted(iterable, [cmp=None], [key=None], [reverse=False)`` collects all the ``sorted(iterable, [cmp=None], [key=None], [reverse=False)`` collects all the
elements of the iterable into a list, sorts the list, and returns the sorted elements of the iterable into a list, sorts the list, and returns the sorted
...@@ -1100,7 +1100,7 @@ Here's a small but realistic example:: ...@@ -1100,7 +1100,7 @@ Here's a small but realistic example::
def log (message, subsystem): def log (message, subsystem):
"Write the contents of 'message' to the specified subsystem." "Write the contents of 'message' to the specified subsystem."
print '%s: %s' % (subsystem, message) print('%s: %s' % (subsystem, message))
... ...
server_log = functools.partial(log, subsystem='server') server_log = functools.partial(log, subsystem='server')
...@@ -1395,6 +1395,6 @@ features in Python 2.5. ...@@ -1395,6 +1395,6 @@ features in Python 2.5.
for elem in slice[:-1]: for elem in slice[:-1]:
sys.stdout.write(str(elem)) sys.stdout.write(str(elem))
sys.stdout.write(', ') sys.stdout.write(', ')
print elem[-1] print(elem[-1])
**************************** ****************************
Regular Expression HOWTO Regular Expression HOWTO
**************************** ****************************
:Author: A.M. Kuchling :Author: A.M. Kuchling
...@@ -263,7 +263,7 @@ performing string substitutions. :: ...@@ -263,7 +263,7 @@ performing string substitutions. ::
>>> import re >>> import re
>>> p = re.compile('ab*') >>> p = re.compile('ab*')
>>> print p >>> p
<re.RegexObject instance at 80b4150> <re.RegexObject instance at 80b4150>
:func:`re.compile` also accepts an optional *flags* argument, used to enable :func:`re.compile` also accepts an optional *flags* argument, used to enable
...@@ -387,7 +387,7 @@ interpreter to print no output. You can explicitly print the result of ...@@ -387,7 +387,7 @@ interpreter to print no output. You can explicitly print the result of
:meth:`match` to make this clear. :: :meth:`match` to make this clear. ::
>>> p.match("") >>> p.match("")
>>> print p.match("") >>> print(p.match(""))
None None
Now, let's try it on a string that it should match, such as ``tempo``. In this Now, let's try it on a string that it should match, such as ``tempo``. In this
...@@ -395,7 +395,7 @@ case, :meth:`match` will return a :class:`MatchObject`, so you should store the ...@@ -395,7 +395,7 @@ case, :meth:`match` will return a :class:`MatchObject`, so you should store the
result in a variable for later use. :: result in a variable for later use. ::
>>> m = p.match('tempo') >>> m = p.match('tempo')
>>> print m >>> m
<_sre.SRE_Match object at 80c4f68> <_sre.SRE_Match object at 80c4f68>
Now you can query the :class:`MatchObject` for information about the matching Now you can query the :class:`MatchObject` for information about the matching
...@@ -432,9 +432,9 @@ will always be zero. However, the :meth:`search` method of :class:`RegexObject` ...@@ -432,9 +432,9 @@ will always be zero. However, the :meth:`search` method of :class:`RegexObject`
instances scans through the string, so the match may not start at zero in that instances scans through the string, so the match may not start at zero in that
case. :: case. ::
>>> print p.match('::: message') >>> print(p.match('::: message'))
None None
>>> m = p.search('::: message') ; print m >>> m = p.search('::: message') ; print(m)
<re.MatchObject instance at 80c9650> <re.MatchObject instance at 80c9650>
>>> m.group() >>> m.group()
'message' 'message'
...@@ -447,9 +447,9 @@ in a variable, and then check if it was ``None``. This usually looks like:: ...@@ -447,9 +447,9 @@ in a variable, and then check if it was ``None``. This usually looks like::
p = re.compile( ... ) p = re.compile( ... )
m = p.match( 'string goes here' ) m = p.match( 'string goes here' )
if m: if m:
print 'Match found: ', m.group() print('Match found: ', m.group())
else: else:
print 'No match' print('No match')
Two :class:`RegexObject` methods return all of the matches for a pattern. Two :class:`RegexObject` methods return all of the matches for a pattern.
:meth:`findall` returns a list of matching strings:: :meth:`findall` returns a list of matching strings::
...@@ -466,7 +466,7 @@ instances as an iterator. [#]_ :: ...@@ -466,7 +466,7 @@ instances as an iterator. [#]_ ::
>>> iterator >>> iterator
<callable-iterator object at 0x401833ac> <callable-iterator object at 0x401833ac>
>>> for match in iterator: >>> for match in iterator:
... print match.span() ... print(match.span())
... ...
(0, 2) (0, 2)
(22, 24) (22, 24)
...@@ -483,7 +483,7 @@ take the same arguments as the corresponding :class:`RegexObject` method, with ...@@ -483,7 +483,7 @@ take the same arguments as the corresponding :class:`RegexObject` method, with
the RE string added as the first argument, and still return either ``None`` or a the RE string added as the first argument, and still return either ``None`` or a
:class:`MatchObject` instance. :: :class:`MatchObject` instance. ::
>>> print re.match(r'From\s+', 'Fromage amk') >>> print(re.match(r'From\s+', 'Fromage amk'))
None None
>>> re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998') >>> re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998')
<re.MatchObject instance at 80c5978> <re.MatchObject instance at 80c5978>
...@@ -674,9 +674,9 @@ given location, they can obviously be matched an infinite number of times. ...@@ -674,9 +674,9 @@ given location, they can obviously be matched an infinite number of times.
For example, if you wish to match the word ``From`` only at the beginning of a For example, if you wish to match the word ``From`` only at the beginning of a
line, the RE to use is ``^From``. :: line, the RE to use is ``^From``. ::
>>> print re.search('^From', 'From Here to Eternity') >>> print(re.search('^From', 'From Here to Eternity'))
<re.MatchObject instance at 80c1520> <re.MatchObject instance at 80c1520>
>>> print re.search('^From', 'Reciting From Memory') >>> print(re.search('^From', 'Reciting From Memory'))
None None
.. % To match a literal \character{\^}, use \regexp{\e\^} or enclose it .. % To match a literal \character{\^}, use \regexp{\e\^} or enclose it
...@@ -686,11 +686,11 @@ given location, they can obviously be matched an infinite number of times. ...@@ -686,11 +686,11 @@ given location, they can obviously be matched an infinite number of times.
Matches at the end of a line, which is defined as either the end of the string, Matches at the end of a line, which is defined as either the end of the string,
or any location followed by a newline character. :: or any location followed by a newline character. ::
>>> print re.search('}$', '{block}') >>> print(re.search('}$', '{block}'))
<re.MatchObject instance at 80adfa8> <re.MatchObject instance at 80adfa8>
>>> print re.search('}$', '{block} ') >>> print(re.search('}$', '{block} '))
None None
>>> print re.search('}$', '{block}\n') >>> print(re.search('}$', '{block}\n'))
<re.MatchObject instance at 80adfa8> <re.MatchObject instance at 80adfa8>
To match a literal ``'$'``, use ``\$`` or enclose it inside a character class, To match a literal ``'$'``, use ``\$`` or enclose it inside a character class,
...@@ -717,11 +717,11 @@ given location, they can obviously be matched an infinite number of times. ...@@ -717,11 +717,11 @@ given location, they can obviously be matched an infinite number of times.
match when it's contained inside another word. :: match when it's contained inside another word. ::
>>> p = re.compile(r'\bclass\b') >>> p = re.compile(r'\bclass\b')
>>> print p.search('no class at all') >>> print(p.search('no class at all'))
<re.MatchObject instance at 80c8f28> <re.MatchObject instance at 80c8f28>
>>> print p.search('the declassified algorithm') >>> print(p.search('the declassified algorithm'))
None None
>>> print p.search('one subclass is') >>> print(p.search('one subclass is'))
None None
There are two subtleties you should remember when using this special sequence. There are two subtleties you should remember when using this special sequence.
...@@ -733,9 +733,9 @@ given location, they can obviously be matched an infinite number of times. ...@@ -733,9 +733,9 @@ given location, they can obviously be matched an infinite number of times.
in front of the RE string. :: in front of the RE string. ::
>>> p = re.compile('\bclass\b') >>> p = re.compile('\bclass\b')
>>> print p.search('no class at all') >>> print(p.search('no class at all'))
None None
>>> print p.search('\b' + 'class' + '\b') >>> print(p.search('\b' + 'class' + '\b') )
<re.MatchObject instance at 80c3ee0> <re.MatchObject instance at 80c3ee0>
Second, inside a character class, where there's no use for this assertion, Second, inside a character class, where there's no use for this assertion,
...@@ -773,7 +773,7 @@ of a group with a repeating qualifier, such as ``*``, ``+``, ``?``, or ...@@ -773,7 +773,7 @@ of a group with a repeating qualifier, such as ``*``, ``+``, ``?``, or
``ab``. :: ``ab``. ::
>>> p = re.compile('(ab)*') >>> p = re.compile('(ab)*')
>>> print p.match('ababababab').span() >>> print(p.match('ababababab').span())
(0, 10) (0, 10)
Groups indicated with ``'('``, ``')'`` also capture the starting and ending Groups indicated with ``'('``, ``')'`` also capture the starting and ending
...@@ -1247,17 +1247,17 @@ It's important to keep this distinction in mind. Remember, :func:`match` will ...@@ -1247,17 +1247,17 @@ It's important to keep this distinction in mind. Remember, :func:`match` will
only report a successful match which will start at 0; if the match wouldn't only report a successful match which will start at 0; if the match wouldn't
start at zero, :func:`match` will *not* report it. :: start at zero, :func:`match` will *not* report it. ::
>>> print re.match('super', 'superstition').span() >>> print(re.match('super', 'superstition').span())
(0, 5) (0, 5)
>>> print re.match('super', 'insuperable') >>> print(re.match('super', 'insuperable'))
None None
On the other hand, :func:`search` will scan forward through the string, On the other hand, :func:`search` will scan forward through the string,
reporting the first match it finds. :: reporting the first match it finds. ::
>>> print re.search('super', 'superstition').span() >>> print(re.search('super', 'superstition').span())
(0, 5) (0, 5)
>>> print re.search('super', 'insuperable').span() >>> print(re.search('super', 'insuperable').span())
(2, 7) (2, 7)
Sometimes you'll be tempted to keep using :func:`re.match`, and just add ``.*`` Sometimes you'll be tempted to keep using :func:`re.match`, and just add ``.*``
...@@ -1286,9 +1286,9 @@ doesn't work because of the greedy nature of ``.*``. :: ...@@ -1286,9 +1286,9 @@ doesn't work because of the greedy nature of ``.*``. ::
>>> s = '<html><head><title>Title</title>' >>> s = '<html><head><title>Title</title>'
>>> len(s) >>> len(s)
32 32
>>> print re.match('<.*>', s).span() >>> print(re.match('<.*>', s).span())
(0, 32) (0, 32)
>>> print re.match('<.*>', s).group() >>> print(re.match('<.*>', s).group())
<html><head><title>Title</title> <html><head><title>Title</title>
The RE matches the ``'<'`` in ``<html>``, and the ``.*`` consumes the rest of The RE matches the ``'<'`` in ``<html>``, and the ``.*`` consumes the rest of
...@@ -1304,7 +1304,7 @@ example, the ``'>'`` is tried immediately after the first ``'<'`` matches, and ...@@ -1304,7 +1304,7 @@ example, the ``'>'`` is tried immediately after the first ``'<'`` matches, and
when it fails, the engine advances a character at a time, retrying the ``'>'`` when it fails, the engine advances a character at a time, retrying the ``'>'``
at every step. This produces just the right result:: at every step. This produces just the right result::
>>> print re.match('<.*?>', s).group() >>> print(re.match('<.*?>', s).group())
<html> <html>
(Note that parsing HTML or XML with regular expressions is painful. (Note that parsing HTML or XML with regular expressions is painful.
......
...@@ -7,6 +7,12 @@ ...@@ -7,6 +7,12 @@
This HOWTO discusses Python's support for Unicode, and explains various problems This HOWTO discusses Python's support for Unicode, and explains various problems
that people commonly encounter when trying to work with Unicode. that people commonly encounter when trying to work with Unicode.
.. XXX fix it
.. warning::
This HOWTO has not yet been updated for Python 3000's string object changes.
Introduction to Unicode Introduction to Unicode
======================= =======================
...@@ -122,8 +128,8 @@ The first encoding you might think of is an array of 32-bit integers. In this ...@@ -122,8 +128,8 @@ The first encoding you might think of is an array of 32-bit integers. In this
representation, the string "Python" would look like this:: representation, the string "Python" would look like this::
P y t h o n P y t h o n
0x50 00 00 00 79 00 00 00 74 00 00 00 68 00 00 00 6f 00 00 00 6e 00 00 00 0x50 00 00 00 79 00 00 00 74 00 00 00 68 00 00 00 6f 00 00 00 6e 00 00 00
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
This representation is straightforward but using it presents a number of This representation is straightforward but using it presents a number of
problems. problems.
...@@ -181,7 +187,7 @@ UTF-8.) UTF-8 uses the following rules: ...@@ -181,7 +187,7 @@ UTF-8.) UTF-8 uses the following rules:
between 128 and 255. between 128 and 255.
3. Code points >0x7ff are turned into three- or four-byte sequences, where each 3. Code points >0x7ff are turned into three- or four-byte sequences, where each
byte of the sequence is between 128 and 255. byte of the sequence is between 128 and 255.
UTF-8 has several convenient properties: UTF-8 has several convenient properties:
1. It can handle any Unicode code point. 1. It can handle any Unicode code point.
...@@ -256,7 +262,7 @@ characters greater than 127 will be treated as errors:: ...@@ -256,7 +262,7 @@ characters greater than 127 will be treated as errors::
>>> unicode('abcdef' + chr(255)) >>> unicode('abcdef' + chr(255))
Traceback (most recent call last): Traceback (most recent call last):
File "<stdin>", line 1, in ? File "<stdin>", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 6: UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 6:
ordinal not in range(128) ordinal not in range(128)
The ``errors`` argument specifies the response when the input string can't be The ``errors`` argument specifies the response when the input string can't be
...@@ -268,7 +274,7 @@ Unicode result). The following examples show the differences:: ...@@ -268,7 +274,7 @@ Unicode result). The following examples show the differences::
>>> unicode('\x80abc', errors='strict') >>> unicode('\x80abc', errors='strict')
Traceback (most recent call last): Traceback (most recent call last):
File "<stdin>", line 1, in ? File "<stdin>", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 0: UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 0:
ordinal not in range(128) ordinal not in range(128)
>>> unicode('\x80abc', errors='replace') >>> unicode('\x80abc', errors='replace')
u'\ufffdabc' u'\ufffdabc'
...@@ -354,7 +360,7 @@ interprets the string using the given encoding:: ...@@ -354,7 +360,7 @@ interprets the string using the given encoding::
>>> u2 = utf8_version.decode('utf-8') # Decode using UTF-8 >>> u2 = utf8_version.decode('utf-8') # Decode using UTF-8
>>> u == u2 # The two strings match >>> u == u2 # The two strings match
True True
The low-level routines for registering and accessing the available encodings are The low-level routines for registering and accessing the available encodings are
found in the :mod:`codecs` module. However, the encoding and decoding functions found in the :mod:`codecs` module. However, the encoding and decoding functions
returned by this module are usually more low-level than is comfortable, so I'm returned by this module are usually more low-level than is comfortable, so I'm
...@@ -366,8 +372,8 @@ covered here. Consult the Python documentation to learn more about this module. ...@@ -366,8 +372,8 @@ covered here. Consult the Python documentation to learn more about this module.
The most commonly used part of the :mod:`codecs` module is the The most commonly used part of the :mod:`codecs` module is the
:func:`codecs.open` function which will be discussed in the section on input and :func:`codecs.open` function which will be discussed in the section on input and
output. output.
Unicode Literals in Python Source Code Unicode Literals in Python Source Code
-------------------------------------- --------------------------------------
...@@ -385,10 +391,10 @@ arbitrary code point. Octal escapes can go up to U+01ff, which is octal 777. ...@@ -385,10 +391,10 @@ arbitrary code point. Octal escapes can go up to U+01ff, which is octal 777.
>>> s = u"a\xac\u1234\u20ac\U00008000" >>> s = u"a\xac\u1234\u20ac\U00008000"
^^^^ two-digit hex escape ^^^^ two-digit hex escape
^^^^^^ four-digit Unicode escape ^^^^^^ four-digit Unicode escape
^^^^^^^^^^ eight-digit Unicode escape ^^^^^^^^^^ eight-digit Unicode escape
>>> for c in s: print ord(c), >>> for c in s: print(ord(c), end=" ")
... ...
97 172 4660 8364 32768 97 172 4660 8364 32768
Using escape sequences for code points greater than 127 is fine in small doses, Using escape sequences for code points greater than 127 is fine in small doses,
...@@ -408,10 +414,10 @@ either the first or second line of the source file:: ...@@ -408,10 +414,10 @@ either the first or second line of the source file::
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: latin-1 -*- # -*- coding: latin-1 -*-
u = u'abcdé' u = u'abcdé'
print ord(u[-1]) print(ord(u[-1]))
The syntax is inspired by Emacs's notation for specifying variables local to a The syntax is inspired by Emacs's notation for specifying variables local to a
file. Emacs supports many different variables, but Python only supports file. Emacs supports many different variables, but Python only supports
'coding'. The ``-*-`` symbols indicate that the comment is special; within 'coding'. The ``-*-`` symbols indicate that the comment is special; within
...@@ -426,15 +432,15 @@ encoding declaration:: ...@@ -426,15 +432,15 @@ encoding declaration::
#!/usr/bin/env python #!/usr/bin/env python
u = u'abcdé' u = u'abcdé'
print ord(u[-1]) print(ord(u[-1]))
When you run it with Python 2.4, it will output the following warning:: When you run it with Python 2.4, it will output the following warning::
amk:~$ python p263.py amk:~$ python p263.py
sys:1: DeprecationWarning: Non-ASCII character '\xe9' sys:1: DeprecationWarning: Non-ASCII character '\xe9'
in file p263.py on line 2, but no encoding declared; in file p263.py on line 2, but no encoding declared;
see http://www.python.org/peps/pep-0263.html for details see http://www.python.org/peps/pep-0263.html for details
Unicode Properties Unicode Properties
------------------ ------------------
...@@ -450,15 +456,15 @@ The following program displays some information about several characters, and ...@@ -450,15 +456,15 @@ The following program displays some information about several characters, and
prints the numeric value of one particular character:: prints the numeric value of one particular character::
import unicodedata import unicodedata
u = unichr(233) + unichr(0x0bf2) + unichr(3972) + unichr(6000) + unichr(13231) u = unichr(233) + unichr(0x0bf2) + unichr(3972) + unichr(6000) + unichr(13231)
for i, c in enumerate(u): for i, c in enumerate(u):
print i, '%04x' % ord(c), unicodedata.category(c), print(i, '%04x' % ord(c), unicodedata.category(c), end=" ")
print unicodedata.name(c) print(unicodedata.name(c))
# Get numeric value of second character # Get numeric value of second character
print unicodedata.numeric(u[1]) print(unicodedata.numeric(u[1]))
When run, this prints:: When run, this prints::
...@@ -545,7 +551,7 @@ Reading Unicode from a file is therefore simple:: ...@@ -545,7 +551,7 @@ Reading Unicode from a file is therefore simple::
import codecs import codecs
f = codecs.open('unicode.rst', encoding='utf-8') f = codecs.open('unicode.rst', encoding='utf-8')
for line in f: for line in f:
print repr(line) print(repr(line))
It's also possible to open files in update mode, allowing both reading and It's also possible to open files in update mode, allowing both reading and
writing:: writing::
...@@ -553,7 +559,7 @@ writing:: ...@@ -553,7 +559,7 @@ writing::
f = codecs.open('test', encoding='utf-8', mode='w+') f = codecs.open('test', encoding='utf-8', mode='w+')
f.write(u'\u4500 blah blah blah\n') f.write(u'\u4500 blah blah blah\n')
f.seek(0) f.seek(0)
print repr(f.readline()[:1]) print(repr(f.readline()[:1]))
f.close() f.close()
Unicode character U+FEFF is used as a byte-order mark (BOM), and is often Unicode character U+FEFF is used as a byte-order mark (BOM), and is often
...@@ -606,8 +612,8 @@ default filesystem encoding is UTF-8, running the following program:: ...@@ -606,8 +612,8 @@ default filesystem encoding is UTF-8, running the following program::
f.close() f.close()
import os import os
print os.listdir('.') print(os.listdir('.'))
print os.listdir(u'.') print(os.listdir(u'.'))
will produce the following output:: will produce the following output::
...@@ -619,7 +625,7 @@ The first list contains UTF-8-encoded filenames, and the second list contains ...@@ -619,7 +625,7 @@ The first list contains UTF-8-encoded filenames, and the second list contains
the Unicode versions. the Unicode versions.
Tips for Writing Unicode-aware Programs Tips for Writing Unicode-aware Programs
--------------------------------------- ---------------------------------------
...@@ -665,7 +671,7 @@ this code:: ...@@ -665,7 +671,7 @@ this code::
unicode_name = filename.decode(encoding) unicode_name = filename.decode(encoding)
f = open(unicode_name, 'r') f = open(unicode_name, 'r')
# ... return contents of file ... # ... return contents of file ...
However, if an attacker could specify the ``'base64'`` encoding, they could pass However, if an attacker could specify the ``'base64'`` encoding, they could pass
``'L2V0Yy9wYXNzd2Q='``, which is the base-64 encoded form of the string ``'L2V0Yy9wYXNzd2Q='``, which is the base-64 encoded form of the string
``'/etc/passwd'``, to read a system file. The above code looks for ``'/'`` ``'/etc/passwd'``, to read a system file. The above code looks for ``'/'``
...@@ -701,7 +707,7 @@ Version 1.02: posted August 16 2005. Corrects factual errors. ...@@ -701,7 +707,7 @@ Version 1.02: posted August 16 2005. Corrects factual errors.
.. comment Describe obscure -U switch somewhere? .. comment Describe obscure -U switch somewhere?
.. comment Describe use of codecs.StreamRecoder and StreamReaderWriter .. comment Describe use of codecs.StreamRecoder and StreamReaderWriter
.. comment .. comment
Original outline: Original outline:
- [ ] Unicode introduction - [ ] Unicode introduction
......
...@@ -134,7 +134,7 @@ This is done as follows:: ...@@ -134,7 +134,7 @@ This is done as follows::
>>> data['location'] = 'Northampton' >>> data['location'] = 'Northampton'
>>> data['language'] = 'Python' >>> data['language'] = 'Python'
>>> url_values = urllib.urlencode(data) >>> url_values = urllib.urlencode(data)
>>> print url_values >>> print(url_values)
name=Somebody+Here&language=Python&location=Northampton name=Somebody+Here&language=Python&location=Northampton
>>> url = 'http://www.example.com/example.cgi' >>> url = 'http://www.example.com/example.cgi'
>>> full_url = url + '?' + url_values >>> full_url = url + '?' + url_values
...@@ -202,7 +202,7 @@ e.g. :: ...@@ -202,7 +202,7 @@ e.g. ::
>>> req = urllib2.Request('http://www.pretend_server.org') >>> req = urllib2.Request('http://www.pretend_server.org')
>>> try: urllib2.urlopen(req) >>> try: urllib2.urlopen(req)
>>> except URLError, e: >>> except URLError, e:
>>> print e.reason >>> print(e.reason)
>>> >>>
(4, 'getaddrinfo failed') (4, 'getaddrinfo failed')
...@@ -311,8 +311,8 @@ geturl, and info, methods. :: ...@@ -311,8 +311,8 @@ geturl, and info, methods. ::
>>> try: >>> try:
>>> urllib2.urlopen(req) >>> urllib2.urlopen(req)
>>> except URLError, e: >>> except URLError, e:
>>> print e.code >>> print(e.code)
>>> print e.read() >>> print(e.read())
>>> >>>
404 404
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
...@@ -339,11 +339,11 @@ Number 1 ...@@ -339,11 +339,11 @@ Number 1
try: try:
response = urlopen(req) response = urlopen(req)
except HTTPError, e: except HTTPError, e:
print 'The server couldn\'t fulfill the request.' print('The server couldn\'t fulfill the request.')
print 'Error code: ', e.code print('Error code: ', e.code)
except URLError, e: except URLError, e:
print 'We failed to reach a server.' print('We failed to reach a server.')
print 'Reason: ', e.reason print('Reason: ', e.reason)
else: else:
# everything is fine # everything is fine
...@@ -364,11 +364,11 @@ Number 2 ...@@ -364,11 +364,11 @@ Number 2
response = urlopen(req) response = urlopen(req)
except URLError, e: except URLError, e:
if hasattr(e, 'reason'): if hasattr(e, 'reason'):
print 'We failed to reach a server.' print('We failed to reach a server.')
print 'Reason: ', e.reason print('Reason: ', e.reason)
elif hasattr(e, 'code'): elif hasattr(e, 'code'):
print 'The server couldn\'t fulfill the request.' print('The server couldn\'t fulfill the request.')
print 'Error code: ', e.code print('Error code: ', e.code)
else: else:
# everything is fine # everything is fine
......
...@@ -383,7 +383,7 @@ an integer, however, use of the handle object is encouraged. ...@@ -383,7 +383,7 @@ an integer, however, use of the handle object is encouraged.
Handle objects provide semantics for :meth:`__bool__` - thus :: Handle objects provide semantics for :meth:`__bool__` - thus ::
if handle: if handle:
print "Yes" print("Yes")
will print ``Yes`` if the handle is currently valid (has not been closed or will print ``Yes`` if the handle is currently valid (has not been closed or
detached). detached).
......
...@@ -64,7 +64,7 @@ then prints out the contents of the database:: ...@@ -64,7 +64,7 @@ then prints out the contents of the database::
# Loop through contents. Other dictionary methods # Loop through contents. Other dictionary methods
# such as .keys(), .values() also work. # such as .keys(), .values() also work.
for k, v in db.iteritems(): for k, v in db.iteritems():
print k, '\t', v print(k, '\t', v)
# Storing a non-string key or value will raise an exception (most # Storing a non-string key or value will raise an exception (most
# likely a TypeError). # likely a TypeError).
......
...@@ -254,7 +254,7 @@ implement its socket handling:: ...@@ -254,7 +254,7 @@ implement its socket handling::
self.close() self.close()
def handle_read(self): def handle_read(self):
print self.recv(8192) print(self.recv(8192))
def writable(self): def writable(self):
return (len(self.buffer) > 0) return (len(self.buffer) > 0)
......
...@@ -80,7 +80,7 @@ Positional and keyword arguments may also be passed to :func:`register` to be ...@@ -80,7 +80,7 @@ Positional and keyword arguments may also be passed to :func:`register` to be
passed along to the registered function when it is called:: passed along to the registered function when it is called::
def goodbye(name, adjective): def goodbye(name, adjective):
print 'Goodbye, %s, it was %s to meet you.' % (name, adjective) print('Goodbye, %s, it was %s to meet you.' % (name, adjective))
import atexit import atexit
atexit.register(goodbye, 'Donny', 'nice') atexit.register(goodbye, 'Donny', 'nice')
...@@ -94,7 +94,7 @@ Usage as a decorator:: ...@@ -94,7 +94,7 @@ Usage as a decorator::
@atexit.register @atexit.register
def goodbye(): def goodbye():
print "You are now leaving the Python sector." print("You are now leaving the Python sector.")
This obviously only works with functions that don't take arguments. This obviously only works with functions that don't take arguments.
...@@ -110,11 +110,11 @@ The :mod:`binascii` module defines the following functions: ...@@ -110,11 +110,11 @@ The :mod:`binascii` module defines the following functions:
use as a checksum algorithm, it is not suitable for use as a general hash use as a checksum algorithm, it is not suitable for use as a general hash
algorithm. Use as follows:: algorithm. Use as follows::
print binascii.crc32("hello world") print(binascii.crc32("hello world"))
# Or, in two pieces: # Or, in two pieces:
crc = binascii.crc32("hello") crc = binascii.crc32("hello")
crc = binascii.crc32(" world", crc) crc = binascii.crc32(" world", crc)
print crc print(crc)
.. function:: b2a_hex(data) .. function:: b2a_hex(data)
......
...@@ -46,16 +46,16 @@ line. The first section contains a number of headers, telling the client what ...@@ -46,16 +46,16 @@ line. The first section contains a number of headers, telling the client what
kind of data is following. Python code to generate a minimal header section kind of data is following. Python code to generate a minimal header section
looks like this:: looks like this::
print "Content-Type: text/html" # HTML is following print("Content-Type: text/html") # HTML is following
print # blank line, end of headers print() # blank line, end of headers
The second section is usually HTML, which allows the client software to display The second section is usually HTML, which allows the client software to display
nicely formatted text with header, in-line images, etc. Here's Python code that nicely formatted text with header, in-line images, etc. Here's Python code that
prints a simple piece of HTML:: prints a simple piece of HTML::
print "<TITLE>CGI script output</TITLE>" print("<TITLE>CGI script output</TITLE>")
print "<H1>This is my first CGI script</H1>" print("<H1>This is my first CGI script</H1>")
print "Hello, world!" print("Hello, world!")
.. _using-the-cgi-module: .. _using-the-cgi-module:
...@@ -104,11 +104,11 @@ string:: ...@@ -104,11 +104,11 @@ string::
form = cgi.FieldStorage() form = cgi.FieldStorage()
if not ("name" in form and "addr" in form): if not ("name" in form and "addr" in form):
print "<H1>Error</H1>" print("<H1>Error</H1>")
print "Please fill in the name and addr fields." print("Please fill in the name and addr fields.")
return return
print "<p>name:", form["name"].value print("<p>name:", form["name"].value)
print "<p>addr:", form["addr"].value print("<p>addr:", form["addr"].value)
...further form processing here... ...further form processing here...
Here the fields, accessed through ``form[key]``, are themselves instances of Here the fields, accessed through ``form[key]``, are themselves instances of
...@@ -505,8 +505,8 @@ you can use an even more robust approach (which only uses built-in modules):: ...@@ -505,8 +505,8 @@ you can use an even more robust approach (which only uses built-in modules)::
import sys import sys
sys.stderr = sys.stdout sys.stderr = sys.stdout
print "Content-Type: text/plain" print("Content-Type: text/plain")
print print()
...your code here... ...your code here...
This relies on the Python interpreter to print the traceback. The content type This relies on the Python interpreter to print the traceback. The content type
......
...@@ -105,7 +105,7 @@ Example:: ...@@ -105,7 +105,7 @@ Example::
>>> from collections import deque >>> from collections import deque
>>> d = deque('ghi') # make a new deque with three items >>> d = deque('ghi') # make a new deque with three items
>>> for elem in d: # iterate over the deque's elements >>> for elem in d: # iterate over the deque's elements
... print elem.upper() ... print(elem.upper())
G G
H H
I I
...@@ -194,7 +194,7 @@ the tasklist if the input stream is not exhausted:: ...@@ -194,7 +194,7 @@ the tasklist if the input stream is not exhausted::
... pending.append(task) ... pending.append(task)
... ...
>>> for value in roundrobin('abc', 'd', 'efgh'): >>> for value in roundrobin('abc', 'd', 'efgh'):
... print value ... print(value)
a a
d d
...@@ -221,7 +221,7 @@ two adjacent nodes into one by grouping them in a list:: ...@@ -221,7 +221,7 @@ two adjacent nodes into one by grouping them in a list::
... d.append(pair) ... d.append(pair)
... return list(d) ... return list(d)
... ...
>>> print maketree('abcdefgh') >>> print(maketree('abcdefgh'))
[[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]] [[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]]
...@@ -386,14 +386,14 @@ Setting the :attr:`default_factory` to :class:`set` makes the ...@@ -386,14 +386,14 @@ Setting the :attr:`default_factory` to :class:`set` makes the
import csv import csv
EmployeeRecord = NamedTuple('EmployeeRecord', 'name age title department paygrade') EmployeeRecord = NamedTuple('EmployeeRecord', 'name age title department paygrade')
for record in starmap(EmployeeRecord, csv.reader(open("employees.csv", "rb"))): for record in starmap(EmployeeRecord, csv.reader(open("employees.csv", "rb"))):
print record print(record)
To cast an individual record stored as :class:`list`, :class:`tuple`, or some To cast an individual record stored as :class:`list`, :class:`tuple`, or some
other iterable type, use the star-operator [#]_ to unpack the values:: other iterable type, use the star-operator [#]_ to unpack the values::
>>> Color = NamedTuple('Color', 'name code') >>> Color = NamedTuple('Color', 'name code')
>>> m = dict(red=1, green=2, blue=3) >>> m = dict(red=1, green=2, blue=3)
>>> print Color(*m.popitem()) >>> print(Color(*m.popitem()))
Color(name='blue', code=3) Color(name='blue', code=3)
.. rubric:: Footnotes .. rubric:: Footnotes
......
...@@ -26,12 +26,12 @@ Functions provided: ...@@ -26,12 +26,12 @@ Functions provided:
@contextmanager @contextmanager
def tag(name): def tag(name):
print "<%s>" % name print("<%s>" % name)
yield yield
print "</%s>" % name print("</%s>" % name)
>>> with tag("h1"): >>> with tag("h1"):
... print "foo" ... print("foo")
... ...
<h1> <h1>
foo foo
...@@ -104,7 +104,7 @@ Functions provided: ...@@ -104,7 +104,7 @@ Functions provided:
with closing(urllib.urlopen('http://www.python.org')) as page: with closing(urllib.urlopen('http://www.python.org')) as page:
for line in page: for line in page:
print line print(line)
without needing to explicitly close ``page``. Even if an error occurs, without needing to explicitly close ``page``. Even if an error occurs,
``page.close()`` will be called when the :keyword:`with` block is exited. ``page.close()`` will be called when the :keyword:`with` block is exited.
......
...@@ -214,32 +214,32 @@ The following example demonstrates how to use the :mod:`Cookie` module. :: ...@@ -214,32 +214,32 @@ The following example demonstrates how to use the :mod:`Cookie` module. ::
>>> C = Cookie.SmartCookie() >>> C = Cookie.SmartCookie()
>>> C["fig"] = "newton" >>> C["fig"] = "newton"
>>> C["sugar"] = "wafer" >>> C["sugar"] = "wafer"
>>> print C # generate HTTP headers >>> print(C) # generate HTTP headers
Set-Cookie: sugar=wafer Set-Cookie: sugar=wafer
Set-Cookie: fig=newton Set-Cookie: fig=newton
>>> print C.output() # same thing >>> print(C.output()) # same thing
Set-Cookie: sugar=wafer Set-Cookie: sugar=wafer
Set-Cookie: fig=newton Set-Cookie: fig=newton
>>> C = Cookie.SmartCookie() >>> C = Cookie.SmartCookie()
>>> C["rocky"] = "road" >>> C["rocky"] = "road"
>>> C["rocky"]["path"] = "/cookie" >>> C["rocky"]["path"] = "/cookie"
>>> print C.output(header="Cookie:") >>> print(C.output(header="Cookie:"))
Cookie: rocky=road; Path=/cookie Cookie: rocky=road; Path=/cookie
>>> print C.output(attrs=[], header="Cookie:") >>> print(C.output(attrs=[], header="Cookie:"))
Cookie: rocky=road Cookie: rocky=road
>>> C = Cookie.SmartCookie() >>> C = Cookie.SmartCookie()
>>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header) >>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
>>> print C >>> print(C)
Set-Cookie: vienna=finger Set-Cookie: vienna=finger
Set-Cookie: chips=ahoy Set-Cookie: chips=ahoy
>>> C = Cookie.SmartCookie() >>> C = Cookie.SmartCookie()
>>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";') >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
>>> print C >>> print(C)
Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;" Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
>>> C = Cookie.SmartCookie() >>> C = Cookie.SmartCookie()
>>> C["oreo"] = "doublestuff" >>> C["oreo"] = "doublestuff"
>>> C["oreo"]["path"] = "/" >>> C["oreo"]["path"] = "/"
>>> print C >>> print(C)
Set-Cookie: oreo=doublestuff; Path=/ Set-Cookie: oreo=doublestuff; Path=/
>>> C = Cookie.SmartCookie() >>> C = Cookie.SmartCookie()
>>> C["twix"] = "none for you" >>> C["twix"] = "none for you"
...@@ -252,7 +252,7 @@ The following example demonstrates how to use the :mod:`Cookie` module. :: ...@@ -252,7 +252,7 @@ The following example demonstrates how to use the :mod:`Cookie` module. ::
'7' '7'
>>> C["string"].value >>> C["string"].value
'seven' 'seven'
>>> print C >>> print(C)
Set-Cookie: number=7 Set-Cookie: number=7
Set-Cookie: string=seven Set-Cookie: string=seven
>>> C = Cookie.SerialCookie() >>> C = Cookie.SerialCookie()
...@@ -262,7 +262,7 @@ The following example demonstrates how to use the :mod:`Cookie` module. :: ...@@ -262,7 +262,7 @@ The following example demonstrates how to use the :mod:`Cookie` module. ::
7 7
>>> C["string"].value >>> C["string"].value
'seven' 'seven'
>>> print C >>> print(C)
Set-Cookie: number="I7\012." Set-Cookie: number="I7\012."
Set-Cookie: string="S'seven'\012p1\012." Set-Cookie: string="S'seven'\012p1\012."
>>> C = Cookie.SmartCookie() >>> C = Cookie.SmartCookie()
...@@ -272,7 +272,7 @@ The following example demonstrates how to use the :mod:`Cookie` module. :: ...@@ -272,7 +272,7 @@ The following example demonstrates how to use the :mod:`Cookie` module. ::
7 7
>>> C["string"].value >>> C["string"].value
'seven' 'seven'
>>> print C >>> print(C)
Set-Cookie: number="I7\012." Set-Cookie: number="I7\012."
Set-Cookie: string=seven Set-Cookie: string=seven
...@@ -390,14 +390,14 @@ The simplest example of reading a CSV file:: ...@@ -390,14 +390,14 @@ The simplest example of reading a CSV file::
import csv import csv
reader = csv.reader(open("some.csv", "rb")) reader = csv.reader(open("some.csv", "rb"))
for row in reader: for row in reader:
print row print(row)
Reading a file with an alternate format:: Reading a file with an alternate format::
import csv import csv
reader = csv.reader(open("passwd", "rb"), delimiter=':', quoting=csv.QUOTE_NONE) reader = csv.reader(open("passwd", "rb"), delimiter=':', quoting=csv.QUOTE_NONE)
for row in reader: for row in reader:
print row print(row)
The corresponding simplest possible writing example is:: The corresponding simplest possible writing example is::
...@@ -420,7 +420,7 @@ A slightly more advanced use of the reader --- catching and reporting errors:: ...@@ -420,7 +420,7 @@ A slightly more advanced use of the reader --- catching and reporting errors::
reader = csv.reader(open(filename, "rb")) reader = csv.reader(open(filename, "rb"))
try: try:
for row in reader: for row in reader:
print row print(row)
except csv.Error as e: except csv.Error as e:
sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
...@@ -429,7 +429,7 @@ done:: ...@@ -429,7 +429,7 @@ done::
import csv import csv
for row in csv.reader(['one,two,three']): for row in csv.reader(['one,two,three']):
print row print(row)
The :mod:`csv` module doesn't directly support reading and writing Unicode, but The :mod:`csv` module doesn't directly support reading and writing Unicode, but
it is 8-bit-clean save for some problems with ASCII NUL characters. So you can it is 8-bit-clean save for some problems with ASCII NUL characters. So you can
......
This diff is collapsed.
...@@ -96,9 +96,9 @@ available in addition to the standard methods. ...@@ -96,9 +96,9 @@ available in addition to the standard methods.
prints every key in the database ``db``, without having to create a list in prints every key in the database ``db``, without having to create a list in
memory that contains them all:: memory that contains them all::
print db.first() print(db.first())
for i in range(1, len(db)): for i in range(1, len(db)):
print db.next() print(db.next())
.. method:: dbhash.previous() .. method:: dbhash.previous()
......
...@@ -1052,7 +1052,7 @@ to work with the :class:`Decimal` class:: ...@@ -1052,7 +1052,7 @@ to work with the :class:`Decimal` class::
def pi(): def pi():
"""Compute Pi to the current precision. """Compute Pi to the current precision.
>>> print pi() >>> print(pi())
3.141592653589793238462643383 3.141592653589793238462643383
""" """
...@@ -1071,13 +1071,13 @@ to work with the :class:`Decimal` class:: ...@@ -1071,13 +1071,13 @@ to work with the :class:`Decimal` class::
def exp(x): def exp(x):
"""Return e raised to the power of x. Result type matches input type. """Return e raised to the power of x. Result type matches input type.
>>> print exp(Decimal(1)) >>> print(exp(Decimal(1)))
2.718281828459045235360287471 2.718281828459045235360287471
>>> print exp(Decimal(2)) >>> print(exp(Decimal(2)))
7.389056098930650227230427461 7.389056098930650227230427461
>>> print exp(2.0) >>> print(exp(2.0))
7.38905609893 7.38905609893
>>> print exp(2+0j) >>> print(exp(2+0j))
(7.38905609893+0j) (7.38905609893+0j)
""" """
...@@ -1095,11 +1095,11 @@ to work with the :class:`Decimal` class:: ...@@ -1095,11 +1095,11 @@ to work with the :class:`Decimal` class::
def cos(x): def cos(x):
"""Return the cosine of x as measured in radians. """Return the cosine of x as measured in radians.
>>> print cos(Decimal('0.5')) >>> print(cos(Decimal('0.5')))
0.8775825618903727161162815826 0.8775825618903727161162815826
>>> print cos(0.5) >>> print(cos(0.5))
0.87758256189 0.87758256189
>>> print cos(0.5+0j) >>> print(cos(0.5+0j))
(0.87758256189+0j) (0.87758256189+0j)
""" """
...@@ -1118,11 +1118,11 @@ to work with the :class:`Decimal` class:: ...@@ -1118,11 +1118,11 @@ to work with the :class:`Decimal` class::
def sin(x): def sin(x):
"""Return the sine of x as measured in radians. """Return the sine of x as measured in radians.
>>> print sin(Decimal('0.5')) >>> print(sin(Decimal('0.5')))
0.4794255386042030002732879352 0.4794255386042030002732879352
>>> print sin(0.5) >>> print(sin(0.5))
0.479425538604 0.479425538604
>>> print sin(0.5+0j) >>> print(sin(0.5+0j))
(0.479425538604+0j) (0.479425538604+0j)
""" """
......
...@@ -194,7 +194,7 @@ ...@@ -194,7 +194,7 @@
>>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
... 'ore\ntree\nemu\n'.splitlines(1)) ... 'ore\ntree\nemu\n'.splitlines(1))
>>> print ''.join(diff), >>> print(''.join(diff), end="")
- one - one
? ^ ? ^
+ ore + ore
...@@ -219,11 +219,11 @@ ...@@ -219,11 +219,11 @@
>>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
... 'ore\ntree\nemu\n'.splitlines(1)) ... 'ore\ntree\nemu\n'.splitlines(1))
>>> diff = list(diff) # materialize the generated delta into a list >>> diff = list(diff) # materialize the generated delta into a list
>>> print ''.join(restore(diff, 1)), >>> print(''.join(restore(diff, 1)), end="")
one one
two two
three three
>>> print ''.join(restore(diff, 2)), >>> print(''.join(restore(diff, 2)), end="")
ore ore
tree tree
emu emu
...@@ -412,8 +412,8 @@ use :meth:`set_seq2` to set the commonly used sequence once and call ...@@ -412,8 +412,8 @@ use :meth:`set_seq2` to set the commonly used sequence once and call
>>> b = "abycdf" >>> b = "abycdf"
>>> s = SequenceMatcher(None, a, b) >>> s = SequenceMatcher(None, a, b)
>>> for tag, i1, i2, j1, j2 in s.get_opcodes(): >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
... print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])) ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])))
delete a[0:1] (q) b[0:0] () delete a[0:1] (q) b[0:0] ()
equal a[1:3] (ab) b[0:2] (ab) equal a[1:3] (ab) b[0:2] (ab)
replace a[3:4] (x) b[2:3] (y) replace a[3:4] (x) b[2:3] (y)
...@@ -488,14 +488,14 @@ This example compares two strings, considering blanks to be "junk:" :: ...@@ -488,14 +488,14 @@ This example compares two strings, considering blanks to be "junk:" ::
sequences. As a rule of thumb, a :meth:`ratio` value over 0.6 means the sequences. As a rule of thumb, a :meth:`ratio` value over 0.6 means the
sequences are close matches:: sequences are close matches::
>>> print round(s.ratio(), 3) >>> print(round(s.ratio(), 3))
0.866 0.866
If you're only interested in where the sequences match, If you're only interested in where the sequences match,
:meth:`get_matching_blocks` is handy:: :meth:`get_matching_blocks` is handy::
>>> for block in s.get_matching_blocks(): >>> for block in s.get_matching_blocks():
... print "a[%d] and b[%d] match for %d elements" % block ... print("a[%d] and b[%d] match for %d elements" % block)
a[0] and b[0] match for 8 elements a[0] and b[0] match for 8 elements
a[8] and b[17] match for 6 elements a[8] and b[17] match for 6 elements
a[14] and b[23] match for 15 elements a[14] and b[23] match for 15 elements
...@@ -509,7 +509,7 @@ If you want to know how to change the first sequence into the second, use ...@@ -509,7 +509,7 @@ If you want to know how to change the first sequence into the second, use
:meth:`get_opcodes`:: :meth:`get_opcodes`::
>>> for opcode in s.get_opcodes(): >>> for opcode in s.get_opcodes():
... print "%6s a[%d:%d] b[%d:%d]" % opcode ... print("%6s a[%d:%d] b[%d:%d]" % opcode)
equal a[0:8] b[0:8] equal a[0:8] b[0:8]
insert a[8:8] b[8:17] insert a[8:8] b[8:17]
equal a[8:14] b[17:23] equal a[8:14] b[17:23]
......
...@@ -309,11 +309,11 @@ your own :class:`DocTestParser` class. ...@@ -309,11 +309,11 @@ your own :class:`DocTestParser` class.
>>> x >>> x
12 12
>>> if x == 13: >>> if x == 13:
... print "yes" ... print("yes")
... else: ... else:
... print "no" ... print("no")
... print "NO" ... print("NO")
... print "NO!!!" ... print("NO!!!")
... ...
no no
NO NO
...@@ -340,7 +340,7 @@ The fine print: ...@@ -340,7 +340,7 @@ The fine print:
>>> def f(x): >>> def f(x):
... r'''Backslashes in a raw docstring: m\n''' ... r'''Backslashes in a raw docstring: m\n'''
>>> print f.__doc__ >>> print(f.__doc__)
Backslashes in a raw docstring: m\n Backslashes in a raw docstring: m\n
Otherwise, the backslash will be interpreted as part of the string. For example, Otherwise, the backslash will be interpreted as part of the string. For example,
...@@ -349,7 +349,7 @@ The fine print: ...@@ -349,7 +349,7 @@ The fine print:
>>> def f(x): >>> def f(x):
... '''Backslashes in a raw docstring: m\\n''' ... '''Backslashes in a raw docstring: m\\n'''
>>> print f.__doc__ >>> print(f.__doc__)
Backslashes in a raw docstring: m\n Backslashes in a raw docstring: m\n
* The starting column doesn't matter:: * The starting column doesn't matter::
...@@ -639,7 +639,7 @@ example. Use ``+`` to enable the named behavior, or ``-`` to disable it. ...@@ -639,7 +639,7 @@ example. Use ``+`` to enable the named behavior, or ``-`` to disable it.
For example, this test passes:: For example, this test passes::
>>> print range(20) #doctest: +NORMALIZE_WHITESPACE >>> print(range(20)) #doctest: +NORMALIZE_WHITESPACE
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19] 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
...@@ -648,18 +648,18 @@ two blanks before the single-digit list elements, and because the actual output ...@@ -648,18 +648,18 @@ two blanks before the single-digit list elements, and because the actual output
is on a single line. This test also passes, and also requires a directive to do is on a single line. This test also passes, and also requires a directive to do
so:: so::
>>> print range(20) # doctest: +ELLIPSIS >>> print(range(20)) # doctest: +ELLIPSIS
[0, 1, ..., 18, 19] [0, 1, ..., 18, 19]
Multiple directives can be used on a single physical line, separated by commas:: Multiple directives can be used on a single physical line, separated by commas::
>>> print range(20) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE >>> print(range(20)) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
[0, 1, ..., 18, 19] [0, 1, ..., 18, 19]
If multiple directive comments are used for a single example, then they are If multiple directive comments are used for a single example, then they are
combined:: combined::
>>> print range(20) # doctest: +ELLIPSIS >>> print(range(20)) # doctest: +ELLIPSIS
... # doctest: +NORMALIZE_WHITESPACE ... # doctest: +NORMALIZE_WHITESPACE
[0, 1, ..., 18, 19] [0, 1, ..., 18, 19]
...@@ -667,7 +667,7 @@ As the previous example shows, you can add ``...`` lines to your example ...@@ -667,7 +667,7 @@ As the previous example shows, you can add ``...`` lines to your example
containing only directives. This can be useful when an example is too long for containing only directives. This can be useful when an example is too long for
a directive to comfortably fit on the same line:: a directive to comfortably fit on the same line::
>>> print range(5) + range(10,20) + range(30,40) + range(50,60) >>> print(range(5) + range(10,20) + range(30,40) + range(50,60))
... # doctest: +ELLIPSIS ... # doctest: +ELLIPSIS
[0, ..., 4, 10, ..., 19, 30, ..., 39, 50, ..., 59] [0, ..., 4, 10, ..., 19, 30, ..., 39, 50, ..., 59]
...@@ -746,9 +746,9 @@ and C libraries vary widely in quality here. :: ...@@ -746,9 +746,9 @@ and C libraries vary widely in quality here. ::
>>> 1./7 # risky >>> 1./7 # risky
0.14285714285714285 0.14285714285714285
>>> print 1./7 # safer >>> print(1./7) # safer
0.142857142857 0.142857142857
>>> print round(1./7, 6) # much safer >>> print(round(1./7, 6)) # much safer
0.142857 0.142857
Numbers of the form ``I/2.**J`` are safe across all platforms, and I often Numbers of the form ``I/2.**J`` are safe across all platforms, and I often
...@@ -1518,7 +1518,7 @@ Doctest provides several mechanisms for debugging doctest examples: ...@@ -1518,7 +1518,7 @@ Doctest provides several mechanisms for debugging doctest examples:
>>> def f(x): >>> def f(x):
... g(x*2) ... g(x*2)
>>> def g(x): >>> def g(x):
... print x+3 ... print(x+3)
... import pdb; pdb.set_trace() ... import pdb; pdb.set_trace()
>>> f(3) >>> f(3)
9 9
...@@ -1533,10 +1533,10 @@ Doctest provides several mechanisms for debugging doctest examples: ...@@ -1533,10 +1533,10 @@ Doctest provides several mechanisms for debugging doctest examples:
-> import pdb; pdb.set_trace() -> import pdb; pdb.set_trace()
(Pdb) list (Pdb) list
1 def g(x): 1 def g(x):
2 print x+3 2 print(x+3)
3 -> import pdb; pdb.set_trace() 3 -> import pdb; pdb.set_trace()
[EOF] [EOF]
(Pdb) print x (Pdb) p x
6 6
(Pdb) step (Pdb) step
--Return-- --Return--
...@@ -1546,7 +1546,7 @@ Doctest provides several mechanisms for debugging doctest examples: ...@@ -1546,7 +1546,7 @@ Doctest provides several mechanisms for debugging doctest examples:
1 def f(x): 1 def f(x):
2 -> g(x*2) 2 -> g(x*2)
[EOF] [EOF]
(Pdb) print x (Pdb) p x
3 3
(Pdb) step (Pdb) step
--Return-- --Return--
...@@ -1571,14 +1571,14 @@ code under the debugger: ...@@ -1571,14 +1571,14 @@ code under the debugger:
returned as a string. For example, :: returned as a string. For example, ::
import doctest import doctest
print doctest.script_from_examples(r""" print(doctest.script_from_examples(r"""
Set x and y to 1 and 2. Set x and y to 1 and 2.
>>> x, y = 1, 2 >>> x, y = 1, 2
Print their sum: Print their sum:
>>> print x+y >>> print(x+y)
3 3
""") """))
displays:: displays::
...@@ -1586,7 +1586,7 @@ code under the debugger: ...@@ -1586,7 +1586,7 @@ code under the debugger:
x, y = 1, 2 x, y = 1, 2
# #
# Print their sum: # Print their sum:
print x+y print(x+y)
# Expected: # Expected:
## 3 ## 3
...@@ -1607,7 +1607,7 @@ code under the debugger: ...@@ -1607,7 +1607,7 @@ code under the debugger:
contains a top-level function :func:`f`, then :: contains a top-level function :func:`f`, then ::
import a, doctest import a, doctest
print doctest.testsource(a, "a.f") print(doctest.testsource(a, "a.f"))
prints a script version of function :func:`f`'s docstring, with doctests prints a script version of function :func:`f`'s docstring, with doctests
converted to code, and the rest placed in comments. converted to code, and the rest placed in comments.
......
...@@ -27,7 +27,7 @@ Here are the public methods of the :class:`Generator` class, imported from the ...@@ -27,7 +27,7 @@ Here are the public methods of the :class:`Generator` class, imported from the
The constructor for the :class:`Generator` class takes a file-like object called The constructor for the :class:`Generator` class takes a file-like object called
*outfp* for an argument. *outfp* must support the :meth:`write` method and be *outfp* for an argument. *outfp* must support the :meth:`write` method and be
usable as the output file in a Python extended print statement. usable as the output file for the :func:`print` function.
Optional *mangle_from_* is a flag that, when ``True``, puts a ``>`` character in Optional *mangle_from_* is a flag that, when ``True``, puts a ``>`` character in
front of any line in the body that starts exactly as ``From``, i.e. ``From`` front of any line in the body that starts exactly as ``From``, i.e. ``From``
...@@ -72,7 +72,7 @@ The other public :class:`Generator` methods are: ...@@ -72,7 +72,7 @@ The other public :class:`Generator` methods are:
Write the string *s* to the underlying file object, i.e. *outfp* passed to Write the string *s* to the underlying file object, i.e. *outfp* passed to
:class:`Generator`'s constructor. This provides just enough file-like API for :class:`Generator`'s constructor. This provides just enough file-like API for
:class:`Generator` instances to be used in extended print statements. :class:`Generator` instances to be used in the :func:`print` function.
As a convenience, see the methods :meth:`Message.as_string` and As a convenience, see the methods :meth:`Message.as_string` and
``str(aMessage)``, a.k.a. :meth:`Message.__str__`, which simplify the generation ``str(aMessage)``, a.k.a. :meth:`Message.__str__`, which simplify the generation
......
...@@ -31,7 +31,7 @@ example:: ...@@ -31,7 +31,7 @@ example::
>>> msg = Message() >>> msg = Message()
>>> h = Header('p\xf6stal', 'iso-8859-1') >>> h = Header('p\xf6stal', 'iso-8859-1')
>>> msg['Subject'] = h >>> msg['Subject'] = h
>>> print msg.as_string() >>> print(msg.as_string())
Subject: =?iso-8859-1?q?p=F6stal?= Subject: =?iso-8859-1?q?p=F6stal?=
......
...@@ -60,6 +60,6 @@ The following function has been added as a useful debugging tool. It should ...@@ -60,6 +60,6 @@ The following function has been added as a useful debugging tool. It should
text/plain text/plain
text/plain text/plain
Optional *fp* is a file-like object to print the output to. It must be suitable Optional *fp* is a file-like object to print the output to. It must be
for Python's extended print statement. *level* is used internally. suitable for Python's :func:`print` function. *level* is used internally.
...@@ -167,7 +167,7 @@ included in the mapping interface. ...@@ -167,7 +167,7 @@ included in the mapping interface.
the ``in`` operator, e.g.:: the ``in`` operator, e.g.::
if 'message-id' in myMessage: if 'message-id' in myMessage:
print 'Message-ID:', myMessage['message-id'] print('Message-ID:', myMessage['message-id'])
.. method:: Message.__getitem__(name) .. method:: Message.__getitem__(name)
...@@ -458,7 +458,7 @@ Here are some additional useful methods: ...@@ -458,7 +458,7 @@ Here are some additional useful methods:
structure:: structure::
>>> for part in msg.walk(): >>> for part in msg.walk():
... print part.get_content_type() ... print(part.get_content_type())
multipart/report multipart/report
text/plain text/plain
message/delivery-status message/delivery-status
......
...@@ -51,7 +51,7 @@ patterns. ...@@ -51,7 +51,7 @@ patterns.
for file in os.listdir('.'): for file in os.listdir('.'):
if fnmatch.fnmatch(file, '*.txt'): if fnmatch.fnmatch(file, '*.txt'):
print file print(file)
.. function:: fnmatchcase(filename, pattern) .. function:: fnmatchcase(filename, pattern)
...@@ -78,7 +78,7 @@ patterns. ...@@ -78,7 +78,7 @@ patterns.
>>> regex >>> regex
'.*\\.txt$' '.*\\.txt$'
>>> reobj = re.compile(regex) >>> reobj = re.compile(regex)
>>> print reobj.match('foobar.txt') >>> print(reobj.match('foobar.txt'))
<_sre.SRE_Match object at 0x...> <_sre.SRE_Match object at 0x...>
......
...@@ -325,7 +325,7 @@ available. They are listed here in alphabetical order. ...@@ -325,7 +325,7 @@ available. They are listed here in alphabetical order.
``(1, seq[1])``, ``(2, seq[2])``, .... For example:: ``(1, seq[1])``, ``(2, seq[2])``, .... For example::
>>> for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter')]: >>> for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter')]:
>>> print i, season >>> print(i, season)
0 Spring 0 Spring
1 Summer 1 Summer
2 Fall 2 Fall
...@@ -350,7 +350,7 @@ available. They are listed here in alphabetical order. ...@@ -350,7 +350,7 @@ available. They are listed here in alphabetical order.
the evaluated expression. Syntax errors are reported as exceptions. Example:: the evaluated expression. Syntax errors are reported as exceptions. Example::
>>> x = 1 >>> x = 1
>>> print eval('x+1') >>> eval('x+1')
2 2
This function can also be used to execute arbitrary code objects (such as those This function can also be used to execute arbitrary code objects (such as those
......
...@@ -92,14 +92,14 @@ The :mod:`functools` module defines the following functions: ...@@ -92,14 +92,14 @@ The :mod:`functools` module defines the following functions:
>>> def my_decorator(f): >>> def my_decorator(f):
... @wraps(f) ... @wraps(f)
... def wrapper(*args, **kwds): ... def wrapper(*args, **kwds):
... print 'Calling decorated function' ... print('Calling decorated function')
... return f(*args, **kwds) ... return f(*args, **kwds)
... return wrapper ... return wrapper
... ...
>>> @my_decorator >>> @my_decorator
... def example(): ... def example():
... """Docstring""" ... """Docstring"""
... print 'Called example function' ... print('Called example function')
... ...
>>> example() >>> example()
Calling decorated function Calling decorated function
......
...@@ -93,7 +93,7 @@ methods: ...@@ -93,7 +93,7 @@ methods:
k = db.firstkey() k = db.firstkey()
while k != None: while k != None:
print k print(k)
k = db.nextkey(k) k = db.nextkey(k)
......
...@@ -112,7 +112,7 @@ In a script, typical usage is something like this:: ...@@ -112,7 +112,7 @@ In a script, typical usage is something like this::
opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="]) opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
except getopt.GetoptError as err: except getopt.GetoptError as err:
# print help information and exit: # print help information and exit:
print str(err) # will print something like "option -a not recognized" print(err) # will print something like "option -a not recognized"
usage() usage()
sys.exit(2) sys.exit(2)
output = None output = None
......
...@@ -126,7 +126,7 @@ Here's an example of typical usage for this API:: ...@@ -126,7 +126,7 @@ Here's an example of typical usage for this API::
gettext.textdomain('myapplication') gettext.textdomain('myapplication')
_ = gettext.gettext _ = gettext.gettext
# ... # ...
print _('This is a translatable string.') print(_('This is a translatable string.'))
Class-based API Class-based API
...@@ -201,7 +201,7 @@ the built-in namespace as the function :func:`_`. ...@@ -201,7 +201,7 @@ the built-in namespace as the function :func:`_`.
candidates for translation, by wrapping them in a call to the :func:`_` candidates for translation, by wrapping them in a call to the :func:`_`
function, like this:: function, like this::
print _('This string will be translated.') print(_('This string will be translated.'))
For convenience, you want the :func:`_` function to be installed in Python's For convenience, you want the :func:`_` function to be installed in Python's
builtin namespace, so it is easily accessible in all modules of your builtin namespace, so it is easily accessible in all modules of your
...@@ -446,7 +446,7 @@ version has a slightly different API. Its documented usage was:: ...@@ -446,7 +446,7 @@ version has a slightly different API. Its documented usage was::
import gettext import gettext
cat = gettext.Catalog(domain, localedir) cat = gettext.Catalog(domain, localedir)
_ = cat.gettext _ = cat.gettext
print _('hello world') print(_('hello world'))
For compatibility with this older module, the function :func:`Catalog` is an For compatibility with this older module, the function :func:`Catalog` is an
alias for the :func:`translation` function described above. alias for the :func:`translation` function described above.
...@@ -604,7 +604,7 @@ translation until later. A classic example is:: ...@@ -604,7 +604,7 @@ translation until later. A classic example is::
] ]
# ... # ...
for a in animals: for a in animals:
print a print(a)
Here, you want to mark the strings in the ``animals`` list as being Here, you want to mark the strings in the ``animals`` list as being
translatable, but you don't actually want to translate them until they are translatable, but you don't actually want to translate them until they are
...@@ -625,7 +625,7 @@ Here is one way you can handle this situation:: ...@@ -625,7 +625,7 @@ Here is one way you can handle this situation::
# ... # ...
for a in animals: for a in animals:
print _(a) print(_(a))
This works because the dummy definition of :func:`_` simply returns the string This works because the dummy definition of :func:`_` simply returns the string
unchanged. And this dummy definition will temporarily override any definition unchanged. And this dummy definition will temporarily override any definition
...@@ -649,7 +649,7 @@ Another way to handle this is with the following example:: ...@@ -649,7 +649,7 @@ Another way to handle this is with the following example::
# ... # ...
for a in animals: for a in animals:
print _(a) print(_(a))
In this case, you are marking translatable strings with the function :func:`N_`, In this case, you are marking translatable strings with the function :func:`N_`,
[#]_ which won't conflict with any definition of :func:`_`. However, you will [#]_ which won't conflict with any definition of :func:`_`. However, you will
......
...@@ -77,10 +77,10 @@ Example of use:: ...@@ -77,10 +77,10 @@ Example of use::
>>> while heap: >>> while heap:
... ordered.append(heappop(heap)) ... ordered.append(heappop(heap))
... ...
>>> print ordered >>> ordered
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> data.sort() >>> data.sort()
>>> print data == ordered >>> data == ordered
True True
>>> >>>
......
...@@ -171,8 +171,8 @@ As a basic example, below is a very basic HTML parser that uses the ...@@ -171,8 +171,8 @@ As a basic example, below is a very basic HTML parser that uses the
class MyHTMLParser(HTMLParser): class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs): def handle_starttag(self, tag, attrs):
print "Encountered the beginning of a %s tag" % tag print("Encountered the beginning of a %s tag" % tag)
def handle_endtag(self, tag): def handle_endtag(self, tag):
print "Encountered the end of a %s tag" % tag print("Encountered the end of a %s tag" % tag)
...@@ -475,12 +475,12 @@ Here is an example session that uses the ``GET`` method:: ...@@ -475,12 +475,12 @@ Here is an example session that uses the ``GET`` method::
>>> conn = httplib.HTTPConnection("www.python.org") >>> conn = httplib.HTTPConnection("www.python.org")
>>> conn.request("GET", "/index.html") >>> conn.request("GET", "/index.html")
>>> r1 = conn.getresponse() >>> r1 = conn.getresponse()
>>> print r1.status, r1.reason >>> print(r1.status, r1.reason)
200 OK 200 OK
>>> data1 = r1.read() >>> data1 = r1.read()
>>> conn.request("GET", "/parrot.spam") >>> conn.request("GET", "/parrot.spam")
>>> r2 = conn.getresponse() >>> r2 = conn.getresponse()
>>> print r2.status, r2.reason >>> print(r2.status, r2.reason)
404 Not Found 404 Not Found
>>> data2 = r2.read() >>> data2 = r2.read()
>>> conn.close() >>> conn.close()
...@@ -494,7 +494,7 @@ Here is an example session that shows how to ``POST`` requests:: ...@@ -494,7 +494,7 @@ Here is an example session that shows how to ``POST`` requests::
>>> conn = httplib.HTTPConnection("musi-cal.mojam.com:80") >>> conn = httplib.HTTPConnection("musi-cal.mojam.com:80")
>>> conn.request("POST", "/cgi-bin/query", params, headers) >>> conn.request("POST", "/cgi-bin/query", params, headers)
>>> response = conn.getresponse() >>> response = conn.getresponse()
>>> print response.status, response.reason >>> print(response.status, response.reason)
200 OK 200 OK
>>> data = response.read() >>> data = response.read()
>>> conn.close() >>> conn.close()
......
...@@ -511,7 +511,7 @@ retrieves and prints all messages:: ...@@ -511,7 +511,7 @@ retrieves and prints all messages::
typ, data = M.search(None, 'ALL') typ, data = M.search(None, 'ALL')
for num in data[0].split(): for num in data[0].split():
typ, data = M.fetch(num, '(RFC822)') typ, data = M.fetch(num, '(RFC822)')
print 'Message %s\n%s\n' % (num, data[0][1]) print('Message %s\n%s\n' % (num, data[0][1]))
M.close() M.close()
M.logout() M.logout()
...@@ -385,7 +385,7 @@ can be combined. :: ...@@ -385,7 +385,7 @@ can be combined. ::
>>> amounts = [120.15, 764.05, 823.14] >>> amounts = [120.15, 764.05, 823.14]
>>> for checknum, amount in izip(count(1200), amounts): >>> for checknum, amount in izip(count(1200), amounts):
... print 'Check %d is for $%.2f' % (checknum, amount) ... print('Check %d is for $%.2f' % (checknum, amount))
... ...
Check 1200 is for $120.15 Check 1200 is for $120.15
Check 1201 is for $764.05 Check 1201 is for $764.05
...@@ -393,7 +393,7 @@ can be combined. :: ...@@ -393,7 +393,7 @@ can be combined. ::
>>> import operator >>> import operator
>>> for cube in imap(operator.pow, range(1,5), repeat(3)): >>> for cube in imap(operator.pow, range(1,5), repeat(3)):
... print cube ... print(cube)
... ...
1 1
8 8
...@@ -403,7 +403,7 @@ can be combined. :: ...@@ -403,7 +403,7 @@ can be combined. ::
>>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', >>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura',
... '', 'martin', '', 'walter', '', 'mark'] ... '', 'martin', '', 'walter', '', 'mark']
>>> for name in islice(reportlines, 3, None, 2): >>> for name in islice(reportlines, 3, None, 2):
... print name.title() ... print(name.title())
... ...
Alex Alex
Laura Laura
...@@ -416,7 +416,7 @@ can be combined. :: ...@@ -416,7 +416,7 @@ can be combined. ::
>>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3) >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
>>> di = sorted(d.iteritems(), key=itemgetter(1)) >>> di = sorted(d.iteritems(), key=itemgetter(1))
>>> for k, g in groupby(di, key=itemgetter(1)): >>> for k, g in groupby(di, key=itemgetter(1)):
... print k, map(itemgetter(0), g) ... print(k, map(itemgetter(0), g))
... ...
1 ['a', 'c', 'e'] 1 ['a', 'c', 'e']
2 ['b', 'd', 'f'] 2 ['b', 'd', 'f']
...@@ -427,7 +427,7 @@ can be combined. :: ...@@ -427,7 +427,7 @@ can be combined. ::
# same group. # same group.
>>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28] >>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
>>> for k, g in groupby(enumerate(data), lambda t:t[0]-t[1]): >>> for k, g in groupby(enumerate(data), lambda t:t[0]-t[1]):
... print map(operator.itemgetter(1), g) ... print(map(operator.itemgetter(1), g))
... ...
[1] [1]
[4, 5, 6] [4, 5, 6]
......
...@@ -841,7 +841,7 @@ module. Here is a basic working example:: ...@@ -841,7 +841,7 @@ module. Here is a basic working example::
logging.basicConfig( logging.basicConfig(
format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s") format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
tcpserver = LogRecordSocketReceiver() tcpserver = LogRecordSocketReceiver()
print "About to start TCP server..." print("About to start TCP server...")
tcpserver.serve_until_stopped() tcpserver.serve_until_stopped()
if __name__ == "__main__": if __name__ == "__main__":
......
...@@ -31,7 +31,7 @@ In Python, the following code fragment will do the same:: ...@@ -31,7 +31,7 @@ In Python, the following code fragment will do the same::
import Finder import Finder
f = Finder.Finder() f = Finder.Finder()
print f.get(f.window(1).name) print(f.get(f.window(1).name))
As distributed the Python library includes packages that implement the standard As distributed the Python library includes packages that implement the standard
suites, plus packages that interface to a small number of common applications. suites, plus packages that interface to a small number of common applications.
......
...@@ -1620,7 +1620,7 @@ interesting:: ...@@ -1620,7 +1620,7 @@ interesting::
for message in mailbox.mbox('~/mbox'): for message in mailbox.mbox('~/mbox'):
subject = message['subject'] # Could possibly be None. subject = message['subject'] # Could possibly be None.
if subject and 'python' in subject.lower(): if subject and 'python' in subject.lower():
print subject print(subject)
To copy all mail from a Babyl mailbox to an MH mailbox, converting all of the To copy all mail from a Babyl mailbox to an MH mailbox, converting all of the
format-specific information that can be converted:: format-specific information that can be converted::
......
...@@ -20,10 +20,10 @@ about a newsgroup and print the subjects of the last 10 articles:: ...@@ -20,10 +20,10 @@ about a newsgroup and print the subjects of the last 10 articles::
>>> s = NNTP('news.cwi.nl') >>> s = NNTP('news.cwi.nl')
>>> resp, count, first, last, name = s.group('comp.lang.python') >>> resp, count, first, last, name = s.group('comp.lang.python')
>>> print 'Group', name, 'has', count, 'articles, range', first, 'to', last >>> print('Group', name, 'has', count, 'articles, range', first, 'to', last)
Group comp.lang.python has 59 articles, range 3742 to 3803 Group comp.lang.python has 59 articles, range 3742 to 3803
>>> resp, subs = s.xhdr('subject', first + '-' + last) >>> resp, subs = s.xhdr('subject', first + '-' + last)
>>> for id, sub in subs[-10:]: print id, sub >>> for id, sub in subs[-10:]: print(id, sub)
... ...
3792 Re: Removing elements from a list while iterating... 3792 Re: Removing elements from a list while iterating...
3793 Re: Who likes Info files? 3793 Re: Who likes Info files?
......
...@@ -348,7 +348,7 @@ right up against the option: since ``"-n42"`` (one argument) is equivalent to ...@@ -348,7 +348,7 @@ right up against the option: since ``"-n42"`` (one argument) is equivalent to
``"-n 42"`` (two arguments), the code :: ``"-n 42"`` (two arguments), the code ::
(options, args) = parser.parse_args(["-n42"]) (options, args) = parser.parse_args(["-n42"])
print options.num print(options.num)
will print ``"42"``. will print ``"42"``.
...@@ -646,7 +646,7 @@ Here's what :mod:`optparse`\ -based scripts usually look like:: ...@@ -646,7 +646,7 @@ Here's what :mod:`optparse`\ -based scripts usually look like::
if len(args) != 1: if len(args) != 1:
parser.error("incorrect number of arguments") parser.error("incorrect number of arguments")
if options.verbose: if options.verbose:
print "reading %s..." % options.filename print("reading %s..." % options.filename)
[...] [...]
if __name__ == "__main__": if __name__ == "__main__":
......
...@@ -1215,9 +1215,9 @@ Files and Directories ...@@ -1215,9 +1215,9 @@ Files and Directories
import os import os
from os.path import join, getsize from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'): for root, dirs, files in os.walk('python/Lib/email'):
print root, "consumes", print(root, "consumes", end=" ")
print sum(getsize(join(root, name)) for name in files), print(sum(getsize(join(root, name)) for name in files), end=" ")
print "bytes in", len(files), "non-directory files" print("bytes in", len(files), "non-directory files")
if 'CVS' in dirs: if 'CVS' in dirs:
dirs.remove('CVS') # don't visit CVS directories dirs.remove('CVS') # don't visit CVS directories
......
...@@ -574,11 +574,11 @@ Here's a silly example that *might* shed more light:: ...@@ -574,11 +574,11 @@ Here's a silly example that *might* shed more light::
return 'My name is integer %d' % self.x return 'My name is integer %d' % self.x
i = Integer(7) i = Integer(7)
print i print(i)
p.dump(i) p.dump(i)
datastream = src.getvalue() datastream = src.getvalue()
print repr(datastream) print(repr(datastream))
dst = StringIO(datastream) dst = StringIO(datastream)
up = pickle.Unpickler(dst) up = pickle.Unpickler(dst)
...@@ -597,7 +597,7 @@ Here's a silly example that *might* shed more light:: ...@@ -597,7 +597,7 @@ Here's a silly example that *might* shed more light::
up.persistent_load = persistent_load up.persistent_load = persistent_load
j = up.load() j = up.load()
print j print(j)
In the :mod:`cPickle` module, the unpickler's :attr:`persistent_load` attribute In the :mod:`cPickle` module, the unpickler's :attr:`persistent_load` attribute
can also be set to a Python list, in which case, when the unpickler reaches a can also be set to a Python list, in which case, when the unpickler reaches a
......
...@@ -191,7 +191,7 @@ retrieves and prints all messages:: ...@@ -191,7 +191,7 @@ retrieves and prints all messages::
numMessages = len(M.list()[1]) numMessages = len(M.list()[1])
for i in range(numMessages): for i in range(numMessages):
for j in M.retr(i+1)[1]: for j in M.retr(i+1)[1]:
print j print(j)
At the end of the module, there is a test section that contains a more extensive At the end of the module, there is a test section that contains a more extensive
example of usage. example of usage.
......
...@@ -85,9 +85,10 @@ The :class:`PrettyPrinter` class supports several derivative functions: ...@@ -85,9 +85,10 @@ The :class:`PrettyPrinter` class supports several derivative functions:
.. function:: pprint(object[, stream[, indent[, width[, depth]]]]) .. function:: pprint(object[, stream[, indent[, width[, depth]]]])
Prints the formatted representation of *object* on *stream*, followed by a Prints the formatted representation of *object* on *stream*, followed by a
newline. If *stream* is omitted, ``sys.stdout`` is used. This may be used in newline. If *stream* is omitted, ``sys.stdout`` is used. This may be used
the interactive interpreter instead of a :keyword:`print` statement for in the interactive interpreter instead of the :func:`print` function for
inspecting values. *indent*, *width* and *depth* will be passed to the inspecting values (you can even reassign ``print = pprint.pprint`` for use
within a scope). *indent*, *width* and *depth* will be passed to the
:class:`PrettyPrinter` constructor as formatting parameters. :: :class:`PrettyPrinter` constructor as formatting parameters. ::
>>> stuff = sys.path[:] >>> stuff = sys.path[:]
......
...@@ -577,7 +577,7 @@ discussion in section Limitations above). :: ...@@ -577,7 +577,7 @@ discussion in section Limitations above). ::
import profile import profile
pr = profile.Profile() pr = profile.Profile()
for i in range(5): for i in range(5):
print pr.calibrate(10000) print(pr.calibrate(10000))
The method executes the number of Python calls given by the argument, directly The method executes the number of Python calls given by the argument, directly
and again under the profiler, measuring the time for both. It then computes the and again under the profiler, measuring the time for both. It then computes the
......
...@@ -494,11 +494,11 @@ arguments. :: ...@@ -494,11 +494,11 @@ arguments. ::
# 3 handler functions # 3 handler functions
def start_element(name, attrs): def start_element(name, attrs):
print 'Start element:', name, attrs print('Start element:', name, attrs)
def end_element(name): def end_element(name):
print 'End element:', name print('End element:', name)
def char_data(data): def char_data(data):
print 'Character data:', repr(data) print('Character data:', repr(data))
p = xml.parsers.expat.ParserCreate() p = xml.parsers.expat.ParserCreate()
......
...@@ -129,5 +129,5 @@ for file objects could be added:: ...@@ -129,5 +129,5 @@ for file objects could be added::
return `obj` return `obj`
aRepr = MyRepr() aRepr = MyRepr()
print aRepr.repr(sys.stdin) # prints '<stdin>' print(aRepr.repr(sys.stdin)) # prints '<stdin>'
...@@ -33,7 +33,7 @@ automatic :kbd:`Tab` completion:: ...@@ -33,7 +33,7 @@ automatic :kbd:`Tab` completion::
try: try:
import readline import readline
except ImportError: except ImportError:
print "Module readline not available." print("Module readline not available.")
else: else:
import rlcompleter import rlcompleter
readline.parse_and_bind("tab: complete") readline.parse_and_bind("tab: complete")
......
...@@ -30,14 +30,14 @@ Example:: ...@@ -30,14 +30,14 @@ Example::
>>> import sched, time >>> import sched, time
>>> s=sched.scheduler(time.time, time.sleep) >>> s=sched.scheduler(time.time, time.sleep)
>>> def print_time(): print "From print_time", time.time() >>> def print_time(): print("From print_time", time.time())
... ...
>>> def print_some_times(): >>> def print_some_times():
... print time.time() ... print(time.time())
... s.enter(5, 1, print_time, ()) ... s.enter(5, 1, print_time, ())
... s.enter(10, 1, print_time, ()) ... s.enter(10, 1, print_time, ())
... s.run() ... s.run()
... print time.time() ... print(time.time())
... ...
>>> print_some_times() >>> print_some_times()
930343690.257 930343690.257
......
...@@ -143,7 +143,7 @@ be sent, and the handler raises an exception. :: ...@@ -143,7 +143,7 @@ be sent, and the handler raises an exception. ::
import signal, os import signal, os
def handler(signum, frame): def handler(signum, frame):
print 'Signal handler called with signal', signum print('Signal handler called with signal', signum)
raise IOError("Couldn't open device!") raise IOError("Couldn't open device!")
# Set the signal handler and a 5-second alarm # Set the signal handler and a 5-second alarm
......
...@@ -143,12 +143,12 @@ server:: ...@@ -143,12 +143,12 @@ server::
import xmlrpclib import xmlrpclib
s = xmlrpclib.Server('http://localhost:8000') s = xmlrpclib.Server('http://localhost:8000')
print s.pow(2,3) # Returns 2**3 = 8 print(s.pow(2,3)) # Returns 2**3 = 8
print s.add(2,3) # Returns 5 print(s.add(2,3)) # Returns 5
print s.div(5,2) # Returns 5//2 = 2 print(s.div(5,2)) # Returns 5//2 = 2
# Print list of available methods # Print list of available methods
print s.system.listMethods() print(s.system.listMethods())
CGIXMLRPCRequestHandler CGIXMLRPCRequestHandler
......
...@@ -317,7 +317,7 @@ example doesn't do any processing of the :rfc:`822` headers. In particular, the ...@@ -317,7 +317,7 @@ example doesn't do any processing of the :rfc:`822` headers. In particular, the
fromaddr = prompt("From: ") fromaddr = prompt("From: ")
toaddrs = prompt("To: ").split() toaddrs = prompt("To: ").split()
print "Enter message, end with ^D (Unix) or ^Z (Windows):" print("Enter message, end with ^D (Unix) or ^Z (Windows):")
# Add the From: and To: headers at the start! # Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n" msg = ("From: %s\r\nTo: %s\r\n\r\n"
...@@ -331,7 +331,7 @@ example doesn't do any processing of the :rfc:`822` headers. In particular, the ...@@ -331,7 +331,7 @@ example doesn't do any processing of the :rfc:`822` headers. In particular, the
break break
msg = msg + line msg = msg + line
print "Message length is " + repr(len(msg)) print("Message length is", len(msg))
server = smtplib.SMTP('localhost') server = smtplib.SMTP('localhost')
server.set_debuglevel(1) server.set_debuglevel(1)
......
...@@ -730,7 +730,7 @@ The first two examples support IPv4 only. :: ...@@ -730,7 +730,7 @@ The first two examples support IPv4 only. ::
s.bind((HOST, PORT)) s.bind((HOST, PORT))
s.listen(1) s.listen(1)
conn, addr = s.accept() conn, addr = s.accept()
print 'Connected by', addr print('Connected by', addr)
while 1: while 1:
data = conn.recv(1024) data = conn.recv(1024)
if not data: break if not data: break
...@@ -749,7 +749,7 @@ The first two examples support IPv4 only. :: ...@@ -749,7 +749,7 @@ The first two examples support IPv4 only. ::
s.send('Hello, world') s.send('Hello, world')
data = s.recv(1024) data = s.recv(1024)
s.close() s.close()
print 'Received', repr(data) print('Received', repr(data))
The next two examples are identical to the above two, but support both IPv4 and The next two examples are identical to the above two, but support both IPv4 and
IPv6. The server side will listen to the first address family available (it IPv6. The server side will listen to the first address family available (it
...@@ -781,10 +781,10 @@ sends traffic to the first one connected successfully. :: ...@@ -781,10 +781,10 @@ sends traffic to the first one connected successfully. ::
continue continue
break break
if s is None: if s is None:
print 'could not open socket' print('could not open socket')
sys.exit(1) sys.exit(1)
conn, addr = s.accept() conn, addr = s.accept()
print 'Connected by', addr print('Connected by', addr)
while 1: while 1:
data = conn.recv(1024) data = conn.recv(1024)
if not data: break if not data: break
...@@ -815,10 +815,10 @@ sends traffic to the first one connected successfully. :: ...@@ -815,10 +815,10 @@ sends traffic to the first one connected successfully. ::
continue continue
break break
if s is None: if s is None:
print 'could not open socket' print('could not open socket')
sys.exit(1) sys.exit(1)
s.send('Hello, world') s.send('Hello, world')
data = s.recv(1024) data = s.recv(1024)
s.close() s.close()
print 'Received', repr(data) print('Received', repr(data))
...@@ -79,7 +79,7 @@ This example uses the iterator form:: ...@@ -79,7 +79,7 @@ This example uses the iterator form::
>>> c = conn.cursor() >>> c = conn.cursor()
>>> c.execute('select * from stocks order by price') >>> c.execute('select * from stocks order by price')
>>> for row in c: >>> for row in c:
... print row ... print(row)
... ...
(u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001) (u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)
(u'2006-03-28', u'BUY', u'IBM', 1000, 45.0) (u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
......
...@@ -297,8 +297,8 @@ sends some bytes, and reads part of the response:: ...@@ -297,8 +297,8 @@ sends some bytes, and reads part of the response::
ssl_sock.connect(('www.verisign.com', 443)) ssl_sock.connect(('www.verisign.com', 443))
print repr(ssl_sock.getpeername()) print(repr(ssl_sock.getpeername()))
print pprint.pformat(ssl_sock.getpeercert()) pprint.pprint(ssl_sock.getpeercert())
# Set a simple HTTP request -- use httplib in actual code. # Set a simple HTTP request -- use httplib in actual code.
ssl_sock.write("""GET / HTTP/1.0\r ssl_sock.write("""GET / HTTP/1.0\r
......
...@@ -22,8 +22,6 @@ interpreter. ...@@ -22,8 +22,6 @@ interpreter.
The principal built-in types are numerics, sequences, mappings, files, classes, The principal built-in types are numerics, sequences, mappings, files, classes,
instances and exceptions. instances and exceptions.
.. index:: statement: print
Some operations are supported by several object types; in particular, Some operations are supported by several object types; in particular,
practically all objects can be compared, tested for truth value, and converted practically all objects can be compared, tested for truth value, and converted
to a string (with the :func:`repr` function or the slightly different to a string (with the :func:`repr` function or the slightly different
...@@ -1976,7 +1974,7 @@ Files have the following methods: ...@@ -1976,7 +1974,7 @@ Files have the following methods:
A file object is its own iterator, for example ``iter(f)`` returns *f* (unless A file object is its own iterator, for example ``iter(f)`` returns *f* (unless
*f* is closed). When a file is used as an iterator, typically in a *f* is closed). When a file is used as an iterator, typically in a
:keyword:`for` loop (for example, ``for line in f: print line``), the :keyword:`for` loop (for example, ``for line in f: print(line)``), the
:meth:`__next__` method is called repeatedly. This method returns the next :meth:`__next__` method is called repeatedly. This method returns the next
input line, or raises :exc:`StopIteration` when EOF is hit when the file is open input line, or raises :exc:`StopIteration` when EOF is hit when the file is open
for reading (behavior is undefined when the file is open for writing). In order for reading (behavior is undefined when the file is open for writing). In order
...@@ -2133,23 +2131,6 @@ the particular object. ...@@ -2133,23 +2131,6 @@ the particular object.
mode the value of this attribute will be ``None``. mode the value of this attribute will be ``None``.
.. attribute:: file.softspace
Boolean that indicates whether a space character needs to be printed before
another value when using the :keyword:`print` statement. Classes that are trying
to simulate a file object should also have a writable :attr:`softspace`
attribute, which should be initialized to zero. This will be automatic for most
classes implemented in Python (care may be needed for objects that override
attribute access); types implemented in C will have to provide a writable
:attr:`softspace` attribute.
.. note::
This attribute is not used to control the :keyword:`print` statement, but to
allow the implementation of :keyword:`print` to keep track of its internal
state.
.. _typecontextmanager: .. _typecontextmanager:
Context Manager Types Context Manager Types
......
...@@ -495,7 +495,7 @@ always available. ...@@ -495,7 +495,7 @@ always available.
File objects corresponding to the interpreter's standard input, output and error File objects corresponding to the interpreter's standard input, output and error
streams. ``stdin`` is used for all interpreter input except for scripts. streams. ``stdin`` is used for all interpreter input except for scripts.
``stdout`` is used for the output of :keyword:`print` and expression statements. ``stdout`` is used for the output of :func:`print` and expression statements.
The interpreter's own prompts and (almost all of) its error messages go to The interpreter's own prompts and (almost all of) its error messages go to
``stderr``. ``stdout`` and ``stderr`` needn't be built-in file objects: any ``stderr``. ``stdout`` and ``stderr`` needn't be built-in file objects: any
object is acceptable as long as it has a :meth:`write` method that takes a object is acceptable as long as it has a :meth:`write` method that takes a
......
...@@ -26,9 +26,9 @@ described below. ...@@ -26,9 +26,9 @@ described below.
If *file_or_dir* is a directory and not a symbolic link, then recursively If *file_or_dir* is a directory and not a symbolic link, then recursively
descend the directory tree named by *file_or_dir*, checking all :file:`.py` descend the directory tree named by *file_or_dir*, checking all :file:`.py`
files along the way. If *file_or_dir* is an ordinary Python source file, it is files along the way. If *file_or_dir* is an ordinary Python source file, it
checked for whitespace related problems. The diagnostic messages are written to is checked for whitespace related problems. The diagnostic messages are
standard output using the print statement. written to standard output using the :func:`print` function.
.. data:: verbose .. data:: verbose
......
...@@ -90,9 +90,9 @@ objects:: ...@@ -90,9 +90,9 @@ objects::
"""Substitute Decimals for floats in a string of statements. """Substitute Decimals for floats in a string of statements.
>>> from decimal import Decimal >>> from decimal import Decimal
>>> s = 'print +21.3e-5*-.1234/81.7' >>> s = 'print(+21.3e-5*-.1234/81.7)'
>>> decistmt(s) >>> decistmt(s)
"print +Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7')" "print(+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7'))"
>>> exec(s) >>> exec(s)
-3.21716034272e-007 -3.21716034272e-007
......
...@@ -32,13 +32,13 @@ form of suite can contain nested compound statements; the following is illegal, ...@@ -32,13 +32,13 @@ form of suite can contain nested compound statements; the following is illegal,
mostly because it wouldn't be clear to which :keyword:`if` clause a following mostly because it wouldn't be clear to which :keyword:`if` clause a following
:keyword:`else` clause would belong: :: :keyword:`else` clause would belong: ::
if test1: if test2: print x if test1: if test2: print(x)
Also note that the semicolon binds tighter than the colon in this context, so Also note that the semicolon binds tighter than the colon in this context, so
that in the following example, either all or none of the :keyword:`print` that in the following example, either all or none of the :func:`print` calls are
statements are executed:: executed::
if x < y < z: print x; print y; print z if x < y < z: print(x); print(y); print(z)
Summarizing: Summarizing:
......
...@@ -376,7 +376,7 @@ Here is a simple example that demonstrates the behavior of generators and ...@@ -376,7 +376,7 @@ Here is a simple example that demonstrates the behavior of generators and
generator functions:: generator functions::
>>> def echo(value=None): >>> def echo(value=None):
... print "Execution starts when 'next()' is called for the first time." ... print("Execution starts when 'next()' is called for the first time.")
... try: ... try:
... while True: ... while True:
... try: ... try:
...@@ -387,15 +387,15 @@ generator functions:: ...@@ -387,15 +387,15 @@ generator functions::
... except Exception, e: ... except Exception, e:
... value = e ... value = e
... finally: ... finally:
... print "Don't forget to clean up when 'close()' is called." ... print("Don't forget to clean up when 'close()' is called.")
... ...
>>> generator = echo(1) >>> generator = echo(1)
>>> print generator.next() >>> print(generator.next())
Execution starts when 'next()' is called for the first time. Execution starts when 'next()' is called for the first time.
1 1
>>> print generator.next() >>> print(generator.next())
None None
>>> print generator.send(2) >>> print(generator.send(2))
2 2
>>> generator.throw(TypeError, "spam") >>> generator.throw(TypeError, "spam")
TypeError('spam',) TypeError('spam',)
...@@ -640,7 +640,7 @@ A consequence of this is that although the ``*expression`` syntax appears ...@@ -640,7 +640,7 @@ A consequence of this is that although the ``*expression`` syntax appears
(and the ``**expression`` argument, if any -- see below). So:: (and the ``**expression`` argument, if any -- see below). So::
>>> def f(a, b): >>> def f(a, b):
... print a, b ... print(a, b)
... ...
>>> f(b=1, *(2,)) >>> f(b=1, *(2,))
2 1 2 1
......
...@@ -254,7 +254,7 @@ are not safe! For instance, the following program prints ``[0, 2]``:: ...@@ -254,7 +254,7 @@ are not safe! For instance, the following program prints ``[0, 2]``::
x = [0, 1] x = [0, 1]
i = 0 i = 0
i, x[i] = 1, 2 i, x[i] = 1, 2
print x print(x)
.. _augassign: .. _augassign:
......
...@@ -26,7 +26,7 @@ complaint you get while you are still learning Python:: ...@@ -26,7 +26,7 @@ complaint you get while you are still learning Python::
The parser repeats the offending line and displays a little 'arrow' pointing at The parser repeats the offending line and displays a little 'arrow' pointing at
the earliest point in the line where the error was detected. The error is the earliest point in the line where the error was detected. The error is
caused by (or at least detected at) the token *preceding* the arrow: in the caused by (or at least detected at) the token *preceding* the arrow: in the
example, the error is detected at the keyword :keyword:`print`, since a colon example, the error is detected at the function :func:`print`, since a colon
(``':'``) is missing before it. File name and line number are printed so you (``':'``) is missing before it. File name and line number are printed so you
know where to look in case the input came from a script. know where to look in case the input came from a script.
...@@ -181,8 +181,8 @@ desired. :: ...@@ -181,8 +181,8 @@ desired. ::
... print(inst.args) # arguments stored in .args ... print(inst.args) # arguments stored in .args
... print(inst) # __str__ allows args to be printed directly ... print(inst) # __str__ allows args to be printed directly
... x, y = inst # __getitem__ allows args to be unpacked directly ... x, y = inst # __getitem__ allows args to be unpacked directly
... print 'x =', x ... print('x =', x)
... print 'y =', y ... print('y =', y)
... ...
<type 'Exception'> <type 'Exception'>
('spam', 'eggs') ('spam', 'eggs')
...@@ -260,7 +260,7 @@ directly or indirectly. For example:: ...@@ -260,7 +260,7 @@ directly or indirectly. For example::
>>> try: >>> try:
... raise MyError(2*2) ... raise MyError(2*2)
... except MyError as e: ... except MyError as e:
... print 'My exception occurred, value:', e.value ... print('My exception occurred, value:', e.value)
... ...
My exception occurred, value: 4 My exception occurred, value: 4
>>> raise MyError, 'oops!' >>> raise MyError, 'oops!'
......
...@@ -85,7 +85,7 @@ Python's builtin :func:`str` function produces only 12 significant digits, and ...@@ -85,7 +85,7 @@ Python's builtin :func:`str` function produces only 12 significant digits, and
you may wish to use that instead. It's unusual for ``eval(str(x))`` to you may wish to use that instead. It's unusual for ``eval(str(x))`` to
reproduce *x*, but the output may be more pleasant to look at:: reproduce *x*, but the output may be more pleasant to look at::
>>> print str(0.1) >>> print(str(0.1))
0.1 0.1
It's important to realize that this is, in a real sense, an illusion: the value It's important to realize that this is, in a real sense, an illusion: the value
......
...@@ -132,7 +132,7 @@ with zeros. It understands about plus and minus signs:: ...@@ -132,7 +132,7 @@ with zeros. It understands about plus and minus signs::
Using the ``%`` operator looks like this:: Using the ``%`` operator looks like this::
>>> import math >>> import math
>>> print 'The value of PI is approximately %5.3f.' % math.pi >>> print('The value of PI is approximately %5.3f.' % math.pi)
The value of PI is approximately 3.142. The value of PI is approximately 3.142.
If there is more than one format in the string, you need to pass a tuple as If there is more than one format in the string, you need to pass a tuple as
...@@ -140,7 +140,7 @@ right operand, as in this example:: ...@@ -140,7 +140,7 @@ right operand, as in this example::
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678} >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items(): >>> for name, phone in table.items():
... print '%-10s ==> %10d' % (name, phone) ... print('%-10s ==> %10d' % (name, phone))
... ...
Jack ==> 4098 Jack ==> 4098
Dcab ==> 7678 Dcab ==> 7678
...@@ -159,7 +159,7 @@ instead of by position. This can be done by using form ``%(name)format``, as ...@@ -159,7 +159,7 @@ instead of by position. This can be done by using form ``%(name)format``, as
shown here:: shown here::
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table >>> print('Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table)
Jack: 4098; Sjoerd: 4127; Dcab: 8637678 Jack: 4098; Sjoerd: 4127; Dcab: 8637678
This is particularly useful in combination with the new built-in :func:`vars` This is particularly useful in combination with the new built-in :func:`vars`
......
...@@ -111,7 +111,7 @@ example, take a look at this :keyword:`if` statement:: ...@@ -111,7 +111,7 @@ example, take a look at this :keyword:`if` statement::
>>> the_world_is_flat = 1 >>> the_world_is_flat = 1
>>> if the_world_is_flat: >>> if the_world_is_flat:
... print "Be careful not to fall off!" ... print("Be careful not to fall off!")
... ...
Be careful not to fall off! Be careful not to fall off!
...@@ -170,6 +170,8 @@ The script can be given an executable mode, or permission, using the ...@@ -170,6 +170,8 @@ The script can be given an executable mode, or permission, using the
Source Code Encoding Source Code Encoding
-------------------- --------------------
.. XXX out of date!
It is possible to use encodings different than ASCII in Python source files. The It is possible to use encodings different than ASCII in Python source files. The
best way to do it is to put one more special comment line right after the ``#!`` best way to do it is to put one more special comment line right after the ``#!``
line to define the source file encoding:: line to define the source file encoding::
...@@ -191,7 +193,7 @@ to the Euro symbol) and then exit:: ...@@ -191,7 +193,7 @@ to the Euro symbol) and then exit::
# -*- coding: iso-8859-15 -*- # -*- coding: iso-8859-15 -*-
currency = u"€" currency = u"€"
print ord(currency) print(ord(currency))
If your editor supports saving files as ``UTF-8`` with a UTF-8 *byte order mark* If your editor supports saving files as ``UTF-8`` with a UTF-8 *byte order mark*
(aka BOM), you can use that instead of an encoding declaration. IDLE supports (aka BOM), you can use that instead of an encoding declaration. IDLE supports
......
...@@ -44,7 +44,7 @@ width:: ...@@ -44,7 +44,7 @@ width::
... a list of strings instead of one big string with newlines to separate ... a list of strings instead of one big string with newlines to separate
... the wrapped lines.""" ... the wrapped lines."""
... ...
>>> print textwrap.fill(doc, width=40) >>> print(textwrap.fill(doc, width=40))
The wrap() method is just like fill() The wrap() method is just like fill()
except that it returns a list of strings except that it returns a list of strings
instead of one big string with newlines instead of one big string with newlines
...@@ -121,7 +121,7 @@ placeholders such as the current date, image sequence number, or file format:: ...@@ -121,7 +121,7 @@ placeholders such as the current date, image sequence number, or file format::
>>> for i, filename in enumerate(photofiles): >>> for i, filename in enumerate(photofiles):
... base, ext = os.path.splitext(filename) ... base, ext = os.path.splitext(filename)
... newname = t.substitute(d=date, n=i, f=ext) ... newname = t.substitute(d=date, n=i, f=ext)
... print '%s --> %s' % (filename, newname) ... print('%s --> %s' % (filename, newname))
img_1074.jpg --> Ashley_0.jpg img_1074.jpg --> Ashley_0.jpg
img_1076.jpg --> Ashley_1.jpg img_1076.jpg --> Ashley_1.jpg
...@@ -155,7 +155,7 @@ and ``"L"`` representing two and four byte unsigned numbers respectively):: ...@@ -155,7 +155,7 @@ and ``"L"`` representing two and four byte unsigned numbers respectively)::
filename = data[start:start+filenamesize] filename = data[start:start+filenamesize]
start += filenamesize start += filenamesize
extra = data[start:start+extra_size] extra = data[start:start+extra_size]
print filename, hex(crc32), comp_size, uncomp_size print(filename, hex(crc32), comp_size, uncomp_size)
start += extra_size + comp_size # skip to the next header start += extra_size + comp_size # skip to the next header
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment