mirror of
https://github.com/python/cpython.git
synced 2025-08-04 17:08:35 +00:00
Convert all print statements in the docs.
This commit is contained in:
parent
c9879246a2
commit
6911e3ce3f
71 changed files with 351 additions and 388 deletions
|
@ -143,8 +143,8 @@ Object Protocol
|
|||
|
||||
Compute a string representation of object *o*. Returns the string
|
||||
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
|
||||
by the :keyword:`print` statement.
|
||||
Python expression ``str(o)``. Called by the :func:`str` built-in function
|
||||
and, therefore, by the :func:`print` function.
|
||||
|
||||
|
||||
.. cfunction:: PyObject* PyObject_Unicode(PyObject *o)
|
||||
|
|
|
@ -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
|
||||
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
|
||||
the print statement.
|
||||
representation of the object, as this is the representation that will be used,
|
||||
among other things, by the :func:`print` function.
|
||||
|
||||
When this field is not set, :cfunc:`PyObject_Repr` is called to return a string
|
||||
representation.
|
||||
|
|
|
@ -64,7 +64,7 @@ perform some operation on a file. ::
|
|||
{
|
||||
Py_Initialize();
|
||||
PyRun_SimpleString("from time import time,ctime\n"
|
||||
"print 'Today is',ctime(time())\n");
|
||||
"print('Today is', ctime(time()))\n");
|
||||
Py_Finalize();
|
||||
return 0;
|
||||
}
|
||||
|
@ -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::
|
||||
|
||||
def multiply(a,b):
|
||||
print "Will compute", a, "times", b
|
||||
print("Will compute", a, "times", b)
|
||||
c = 0
|
||||
for i in range(0, a):
|
||||
c = c + b
|
||||
|
@ -234,7 +234,7 @@ These two lines initialize the ``numargs`` variable, and make the
|
|||
With these extensions, the Python script can do things like ::
|
||||
|
||||
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
|
||||
Python.
|
||||
|
|
|
@ -826,11 +826,11 @@ increases an internal counter. ::
|
|||
>>> import shoddy
|
||||
>>> s = shoddy.Shoddy(range(3))
|
||||
>>> s.extend(s)
|
||||
>>> print len(s)
|
||||
>>> print(len(s))
|
||||
6
|
||||
>>> print s.increment()
|
||||
>>> print(s.increment())
|
||||
1
|
||||
>>> print s.increment()
|
||||
>>> print(s.increment())
|
||||
2
|
||||
|
||||
.. literalinclude:: ../includes/shoddy.c
|
||||
|
@ -1063,34 +1063,6 @@ Here is a simple example::
|
|||
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
|
||||
|
|
|
@ -59,7 +59,7 @@ its least useful properties.
|
|||
|
||||
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
|
||||
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
|
||||
|
@ -181,7 +181,7 @@ The following is a very popular anti-idiom ::
|
|||
|
||||
def get_status(file):
|
||||
if not os.path.exists(file):
|
||||
print "file not found"
|
||||
print("file not found")
|
||||
sys.exit(1)
|
||||
return open(file).readline()
|
||||
|
||||
|
@ -199,7 +199,7 @@ Here is a better way to do it. ::
|
|||
try:
|
||||
return open(file).readline()
|
||||
except (IOError, OSError):
|
||||
print "file not found"
|
||||
print("file not found")
|
||||
sys.exit(1)
|
||||
|
||||
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
|
|||
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
|
||||
sequence with comparable semantics, for example, yet many people write their own
|
||||
:func:`max`/:func:`min`. Another highly useful function is :func:`reduce`. A
|
||||
classical use of :func:`reduce` is something like ::
|
||||
:func:`max`/:func:`min`. Another highly useful function is
|
||||
: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:])
|
||||
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
|
||||
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::
|
|||
|
||||
>>> L = [1,2,3]
|
||||
>>> it = iter(L)
|
||||
>>> print it
|
||||
>>> it
|
||||
<iterator object at 0x8116870>
|
||||
>>> it.next()
|
||||
1
|
||||
|
@ -221,10 +221,10 @@ be an iterator or some object for which ``iter()`` can create an iterator.
|
|||
These two statements are equivalent::
|
||||
|
||||
for i in iter(obj):
|
||||
print i
|
||||
print(i)
|
||||
|
||||
for i in obj:
|
||||
print i
|
||||
print(i)
|
||||
|
||||
Iterators can be materialized as lists or tuples by using the :func:`list` or
|
||||
:func:`tuple` constructor functions::
|
||||
|
@ -274,7 +274,7 @@ dictionary's keys::
|
|||
>>> 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}
|
||||
>>> for key in m:
|
||||
... print key, m[key]
|
||||
... print(key, m[key])
|
||||
Mar 3
|
||||
Feb 2
|
||||
Aug 8
|
||||
|
@ -316,7 +316,7 @@ elements::
|
|||
|
||||
S = set((2, 3, 5, 7, 11, 13))
|
||||
for i in S:
|
||||
print i
|
||||
print(i)
|
||||
|
||||
|
||||
|
||||
|
@ -568,18 +568,18 @@ the internal counter.
|
|||
And here's an example of changing the counter:
|
||||
|
||||
>>> it = counter(10)
|
||||
>>> print it.next()
|
||||
>>> it.next()
|
||||
0
|
||||
>>> print it.next()
|
||||
>>> it.next()
|
||||
1
|
||||
>>> print it.send(8)
|
||||
>>> it.send(8)
|
||||
8
|
||||
>>> print it.next()
|
||||
>>> it.next()
|
||||
9
|
||||
>>> print it.next()
|
||||
>>> it.next()
|
||||
Traceback (most recent call last):
|
||||
File ``t.py'', line 15, in ?
|
||||
print it.next()
|
||||
it.next()
|
||||
StopIteration
|
||||
|
||||
Because ``yield`` will often be returning ``None``, you should always check for
|
||||
|
@ -721,7 +721,7 @@ indexes at which certain conditions are met::
|
|||
f = open('data.txt', 'r')
|
||||
for i, line in enumerate(f):
|
||||
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
|
||||
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::
|
|||
|
||||
def log (message, 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')
|
||||
|
@ -1395,6 +1395,6 @@ features in Python 2.5.
|
|||
for elem in slice[:-1]:
|
||||
sys.stdout.write(str(elem))
|
||||
sys.stdout.write(', ')
|
||||
print elem[-1]
|
||||
print(elem[-1])
|
||||
|
||||
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
****************************
|
||||
Regular Expression HOWTO
|
||||
Regular Expression HOWTO
|
||||
****************************
|
||||
|
||||
:Author: A.M. Kuchling
|
||||
|
@ -263,7 +263,7 @@ performing string substitutions. ::
|
|||
|
||||
>>> import re
|
||||
>>> p = re.compile('ab*')
|
||||
>>> print p
|
||||
>>> p
|
||||
<re.RegexObject instance at 80b4150>
|
||||
|
||||
: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
|
|||
:meth:`match` to make this clear. ::
|
||||
|
||||
>>> p.match("")
|
||||
>>> print p.match("")
|
||||
>>> print(p.match(""))
|
||||
None
|
||||
|
||||
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
|
|||
result in a variable for later use. ::
|
||||
|
||||
>>> m = p.match('tempo')
|
||||
>>> print m
|
||||
>>> m
|
||||
<_sre.SRE_Match object at 80c4f68>
|
||||
|
||||
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`
|
|||
instances scans through the string, so the match may not start at zero in that
|
||||
case. ::
|
||||
|
||||
>>> print p.match('::: message')
|
||||
>>> print(p.match('::: message'))
|
||||
None
|
||||
>>> m = p.search('::: message') ; print m
|
||||
>>> m = p.search('::: message') ; print(m)
|
||||
<re.MatchObject instance at 80c9650>
|
||||
>>> m.group()
|
||||
'message'
|
||||
|
@ -447,9 +447,9 @@ in a variable, and then check if it was ``None``. This usually looks like::
|
|||
p = re.compile( ... )
|
||||
m = p.match( 'string goes here' )
|
||||
if m:
|
||||
print 'Match found: ', m.group()
|
||||
print('Match found: ', m.group())
|
||||
else:
|
||||
print 'No match'
|
||||
print('No match')
|
||||
|
||||
Two :class:`RegexObject` methods return all of the matches for a pattern.
|
||||
:meth:`findall` returns a list of matching strings::
|
||||
|
@ -466,7 +466,7 @@ instances as an iterator. [#]_ ::
|
|||
>>> iterator
|
||||
<callable-iterator object at 0x401833ac>
|
||||
>>> for match in iterator:
|
||||
... print match.span()
|
||||
... print(match.span())
|
||||
...
|
||||
(0, 2)
|
||||
(22, 24)
|
||||
|
@ -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
|
||||
:class:`MatchObject` instance. ::
|
||||
|
||||
>>> print re.match(r'From\s+', 'Fromage amk')
|
||||
>>> print(re.match(r'From\s+', 'Fromage amk'))
|
||||
None
|
||||
>>> re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998')
|
||||
<re.MatchObject instance at 80c5978>
|
||||
|
@ -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
|
||||
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>
|
||||
>>> print re.search('^From', 'Reciting From Memory')
|
||||
>>> print(re.search('^From', 'Reciting From Memory'))
|
||||
None
|
||||
|
||||
.. % 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.
|
|||
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. ::
|
||||
|
||||
>>> print re.search('}$', '{block}')
|
||||
>>> print(re.search('}$', '{block}'))
|
||||
<re.MatchObject instance at 80adfa8>
|
||||
>>> print re.search('}$', '{block} ')
|
||||
>>> print(re.search('}$', '{block} '))
|
||||
None
|
||||
>>> print re.search('}$', '{block}\n')
|
||||
>>> print(re.search('}$', '{block}\n'))
|
||||
<re.MatchObject instance at 80adfa8>
|
||||
|
||||
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.
|
|||
match when it's contained inside another word. ::
|
||||
|
||||
>>> 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>
|
||||
>>> print p.search('the declassified algorithm')
|
||||
>>> print(p.search('the declassified algorithm'))
|
||||
None
|
||||
>>> print p.search('one subclass is')
|
||||
>>> print(p.search('one subclass is'))
|
||||
None
|
||||
|
||||
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.
|
|||
in front of the RE string. ::
|
||||
|
||||
>>> p = re.compile('\bclass\b')
|
||||
>>> print p.search('no class at all')
|
||||
>>> print(p.search('no class at all'))
|
||||
None
|
||||
>>> print p.search('\b' + 'class' + '\b')
|
||||
>>> print(p.search('\b' + 'class' + '\b') )
|
||||
<re.MatchObject instance at 80c3ee0>
|
||||
|
||||
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
|
|||
``ab``. ::
|
||||
|
||||
>>> p = re.compile('(ab)*')
|
||||
>>> print p.match('ababababab').span()
|
||||
>>> print(p.match('ababababab').span())
|
||||
(0, 10)
|
||||
|
||||
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
|
|||
only report a successful match which will start at 0; if the match wouldn't
|
||||
start at zero, :func:`match` will *not* report it. ::
|
||||
|
||||
>>> print re.match('super', 'superstition').span()
|
||||
>>> print(re.match('super', 'superstition').span())
|
||||
(0, 5)
|
||||
>>> print re.match('super', 'insuperable')
|
||||
>>> print(re.match('super', 'insuperable'))
|
||||
None
|
||||
|
||||
On the other hand, :func:`search` will scan forward through the string,
|
||||
reporting the first match it finds. ::
|
||||
|
||||
>>> print re.search('super', 'superstition').span()
|
||||
>>> print(re.search('super', 'superstition').span())
|
||||
(0, 5)
|
||||
>>> print re.search('super', 'insuperable').span()
|
||||
>>> print(re.search('super', 'insuperable').span())
|
||||
(2, 7)
|
||||
|
||||
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 ``.*``. ::
|
|||
>>> s = '<html><head><title>Title</title>'
|
||||
>>> len(s)
|
||||
32
|
||||
>>> print re.match('<.*>', s).span()
|
||||
>>> print(re.match('<.*>', s).span())
|
||||
(0, 32)
|
||||
>>> print re.match('<.*>', s).group()
|
||||
>>> print(re.match('<.*>', s).group())
|
||||
<html><head><title>Title</title>
|
||||
|
||||
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
|
|||
when it fails, the engine advances a character at a time, retrying the ``'>'``
|
||||
at every step. This produces just the right result::
|
||||
|
||||
>>> print re.match('<.*?>', s).group()
|
||||
>>> print(re.match('<.*?>', s).group())
|
||||
<html>
|
||||
|
||||
(Note that parsing HTML or XML with regular expressions is painful.
|
||||
|
|
|
@ -7,6 +7,12 @@
|
|||
This HOWTO discusses Python's support for Unicode, and explains various problems
|
||||
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
|
||||
=======================
|
||||
|
||||
|
@ -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::
|
||||
|
||||
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
|
||||
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
||||
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
|
||||
|
||||
This representation is straightforward but using it presents a number of
|
||||
problems.
|
||||
|
@ -181,7 +187,7 @@ UTF-8.) UTF-8 uses the following rules:
|
|||
between 128 and 255.
|
||||
3. Code points >0x7ff are turned into three- or four-byte sequences, where each
|
||||
byte of the sequence is between 128 and 255.
|
||||
|
||||
|
||||
UTF-8 has several convenient properties:
|
||||
|
||||
1. It can handle any Unicode code point.
|
||||
|
@ -256,7 +262,7 @@ characters greater than 127 will be treated as errors::
|
|||
>>> unicode('abcdef' + chr(255))
|
||||
Traceback (most recent call last):
|
||||
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)
|
||||
|
||||
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::
|
|||
>>> unicode('\x80abc', errors='strict')
|
||||
Traceback (most recent call last):
|
||||
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)
|
||||
>>> unicode('\x80abc', errors='replace')
|
||||
u'\ufffdabc'
|
||||
|
@ -354,7 +360,7 @@ interprets the string using the given encoding::
|
|||
>>> u2 = utf8_version.decode('utf-8') # Decode using UTF-8
|
||||
>>> u == u2 # The two strings match
|
||||
True
|
||||
|
||||
|
||||
The low-level routines for registering and accessing the available encodings are
|
||||
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
|
||||
|
@ -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
|
||||
:func:`codecs.open` function which will be discussed in the section on input and
|
||||
output.
|
||||
|
||||
|
||||
|
||||
|
||||
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.
|
|||
|
||||
>>> s = u"a\xac\u1234\u20ac\U00008000"
|
||||
^^^^ two-digit hex escape
|
||||
^^^^^^ four-digit Unicode escape
|
||||
^^^^^^ four-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
|
||||
|
||||
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::
|
|||
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: latin-1 -*-
|
||||
|
||||
|
||||
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
|
||||
file. Emacs supports many different variables, but Python only supports
|
||||
'coding'. The ``-*-`` symbols indicate that the comment is special; within
|
||||
|
@ -426,15 +432,15 @@ encoding declaration::
|
|||
|
||||
#!/usr/bin/env python
|
||||
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::
|
||||
|
||||
amk:~$ python p263.py
|
||||
sys:1: DeprecationWarning: Non-ASCII character '\xe9'
|
||||
in file p263.py on line 2, but no encoding declared;
|
||||
sys:1: DeprecationWarning: Non-ASCII character '\xe9'
|
||||
in file p263.py on line 2, but no encoding declared;
|
||||
see http://www.python.org/peps/pep-0263.html for details
|
||||
|
||||
|
||||
|
||||
Unicode Properties
|
||||
------------------
|
||||
|
@ -450,15 +456,15 @@ The following program displays some information about several characters, and
|
|||
prints the numeric value of one particular character::
|
||||
|
||||
import unicodedata
|
||||
|
||||
|
||||
u = unichr(233) + unichr(0x0bf2) + unichr(3972) + unichr(6000) + unichr(13231)
|
||||
|
||||
|
||||
for i, c in enumerate(u):
|
||||
print i, '%04x' % ord(c), unicodedata.category(c),
|
||||
print unicodedata.name(c)
|
||||
|
||||
print(i, '%04x' % ord(c), unicodedata.category(c), end=" ")
|
||||
print(unicodedata.name(c))
|
||||
|
||||
# Get numeric value of second character
|
||||
print unicodedata.numeric(u[1])
|
||||
print(unicodedata.numeric(u[1]))
|
||||
|
||||
When run, this prints::
|
||||
|
||||
|
@ -545,7 +551,7 @@ Reading Unicode from a file is therefore simple::
|
|||
import codecs
|
||||
f = codecs.open('unicode.rst', encoding='utf-8')
|
||||
for line in f:
|
||||
print repr(line)
|
||||
print(repr(line))
|
||||
|
||||
It's also possible to open files in update mode, allowing both reading and
|
||||
writing::
|
||||
|
@ -553,7 +559,7 @@ writing::
|
|||
f = codecs.open('test', encoding='utf-8', mode='w+')
|
||||
f.write(u'\u4500 blah blah blah\n')
|
||||
f.seek(0)
|
||||
print repr(f.readline()[:1])
|
||||
print(repr(f.readline()[:1]))
|
||||
f.close()
|
||||
|
||||
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::
|
|||
f.close()
|
||||
|
||||
import os
|
||||
print os.listdir('.')
|
||||
print os.listdir(u'.')
|
||||
print(os.listdir('.'))
|
||||
print(os.listdir(u'.'))
|
||||
|
||||
will produce the following output::
|
||||
|
||||
|
@ -619,7 +625,7 @@ The first list contains UTF-8-encoded filenames, and the second list contains
|
|||
the Unicode versions.
|
||||
|
||||
|
||||
|
||||
|
||||
Tips for Writing Unicode-aware Programs
|
||||
---------------------------------------
|
||||
|
||||
|
@ -665,7 +671,7 @@ this code::
|
|||
unicode_name = filename.decode(encoding)
|
||||
f = open(unicode_name, 'r')
|
||||
# ... return contents of file ...
|
||||
|
||||
|
||||
However, if an attacker could specify the ``'base64'`` encoding, they could pass
|
||||
``'L2V0Yy9wYXNzd2Q='``, which is the base-64 encoded form of the string
|
||||
``'/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.
|
|||
.. comment Describe obscure -U switch somewhere?
|
||||
.. comment Describe use of codecs.StreamRecoder and StreamReaderWriter
|
||||
|
||||
.. comment
|
||||
.. comment
|
||||
Original outline:
|
||||
|
||||
- [ ] Unicode introduction
|
||||
|
|
|
@ -134,7 +134,7 @@ This is done as follows::
|
|||
>>> data['location'] = 'Northampton'
|
||||
>>> data['language'] = 'Python'
|
||||
>>> url_values = urllib.urlencode(data)
|
||||
>>> print url_values
|
||||
>>> print(url_values)
|
||||
name=Somebody+Here&language=Python&location=Northampton
|
||||
>>> url = 'http://www.example.com/example.cgi'
|
||||
>>> full_url = url + '?' + url_values
|
||||
|
@ -202,7 +202,7 @@ e.g. ::
|
|||
>>> req = urllib2.Request('http://www.pretend_server.org')
|
||||
>>> try: urllib2.urlopen(req)
|
||||
>>> except URLError, e:
|
||||
>>> print e.reason
|
||||
>>> print(e.reason)
|
||||
>>>
|
||||
(4, 'getaddrinfo failed')
|
||||
|
||||
|
@ -311,8 +311,8 @@ geturl, and info, methods. ::
|
|||
>>> try:
|
||||
>>> urllib2.urlopen(req)
|
||||
>>> except URLError, e:
|
||||
>>> print e.code
|
||||
>>> print e.read()
|
||||
>>> print(e.code)
|
||||
>>> print(e.read())
|
||||
>>>
|
||||
404
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
|
||||
|
@ -339,11 +339,11 @@ Number 1
|
|||
try:
|
||||
response = urlopen(req)
|
||||
except HTTPError, e:
|
||||
print 'The server couldn\'t fulfill the request.'
|
||||
print 'Error code: ', e.code
|
||||
print('The server couldn\'t fulfill the request.')
|
||||
print('Error code: ', e.code)
|
||||
except URLError, e:
|
||||
print 'We failed to reach a server.'
|
||||
print 'Reason: ', e.reason
|
||||
print('We failed to reach a server.')
|
||||
print('Reason: ', e.reason)
|
||||
else:
|
||||
# everything is fine
|
||||
|
||||
|
@ -364,11 +364,11 @@ Number 2
|
|||
response = urlopen(req)
|
||||
except URLError, e:
|
||||
if hasattr(e, 'reason'):
|
||||
print 'We failed to reach a server.'
|
||||
print 'Reason: ', e.reason
|
||||
print('We failed to reach a server.')
|
||||
print('Reason: ', e.reason)
|
||||
elif hasattr(e, 'code'):
|
||||
print 'The server couldn\'t fulfill the request.'
|
||||
print 'Error code: ', e.code
|
||||
print('The server couldn\'t fulfill the request.')
|
||||
print('Error code: ', e.code)
|
||||
else:
|
||||
# everything is fine
|
||||
|
||||
|
|
|
@ -383,7 +383,7 @@ an integer, however, use of the handle object is encouraged.
|
|||
Handle objects provide semantics for :meth:`__bool__` - thus ::
|
||||
|
||||
if handle:
|
||||
print "Yes"
|
||||
print("Yes")
|
||||
|
||||
will print ``Yes`` if the handle is currently valid (has not been closed or
|
||||
detached).
|
||||
|
|
|
@ -64,7 +64,7 @@ then prints out the contents of the database::
|
|||
# Loop through contents. Other dictionary methods
|
||||
# such as .keys(), .values() also work.
|
||||
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
|
||||
# likely a TypeError).
|
||||
|
|
|
@ -254,7 +254,7 @@ implement its socket handling::
|
|||
self.close()
|
||||
|
||||
def handle_read(self):
|
||||
print self.recv(8192)
|
||||
print(self.recv(8192))
|
||||
|
||||
def writable(self):
|
||||
return (len(self.buffer) > 0)
|
||||
|
|
|
@ -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::
|
||||
|
||||
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
|
||||
atexit.register(goodbye, 'Donny', 'nice')
|
||||
|
@ -94,7 +94,7 @@ Usage as a decorator::
|
|||
|
||||
@atexit.register
|
||||
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.
|
||||
|
||||
|
|
|
@ -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
|
||||
algorithm. Use as follows::
|
||||
|
||||
print binascii.crc32("hello world")
|
||||
print(binascii.crc32("hello world"))
|
||||
# Or, in two pieces:
|
||||
crc = binascii.crc32("hello")
|
||||
crc = binascii.crc32(" world", crc)
|
||||
print crc
|
||||
print(crc)
|
||||
|
||||
|
||||
.. function:: b2a_hex(data)
|
||||
|
|
|
@ -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
|
||||
looks like this::
|
||||
|
||||
print "Content-Type: text/html" # HTML is following
|
||||
print # blank line, end of headers
|
||||
print("Content-Type: text/html") # HTML is following
|
||||
print() # blank line, end of headers
|
||||
|
||||
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
|
||||
prints a simple piece of HTML::
|
||||
|
||||
print "<TITLE>CGI script output</TITLE>"
|
||||
print "<H1>This is my first CGI script</H1>"
|
||||
print "Hello, world!"
|
||||
print("<TITLE>CGI script output</TITLE>")
|
||||
print("<H1>This is my first CGI script</H1>")
|
||||
print("Hello, world!")
|
||||
|
||||
|
||||
.. _using-the-cgi-module:
|
||||
|
@ -104,11 +104,11 @@ string::
|
|||
|
||||
form = cgi.FieldStorage()
|
||||
if not ("name" in form and "addr" in form):
|
||||
print "<H1>Error</H1>"
|
||||
print "Please fill in the name and addr fields."
|
||||
print("<H1>Error</H1>")
|
||||
print("Please fill in the name and addr fields.")
|
||||
return
|
||||
print "<p>name:", form["name"].value
|
||||
print "<p>addr:", form["addr"].value
|
||||
print("<p>name:", form["name"].value)
|
||||
print("<p>addr:", form["addr"].value)
|
||||
...further form processing here...
|
||||
|
||||
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)::
|
|||
|
||||
import sys
|
||||
sys.stderr = sys.stdout
|
||||
print "Content-Type: text/plain"
|
||||
print
|
||||
print("Content-Type: text/plain")
|
||||
print()
|
||||
...your code here...
|
||||
|
||||
This relies on the Python interpreter to print the traceback. The content type
|
||||
|
|
|
@ -105,7 +105,7 @@ Example::
|
|||
>>> from collections import deque
|
||||
>>> d = deque('ghi') # make a new deque with three items
|
||||
>>> for elem in d: # iterate over the deque's elements
|
||||
... print elem.upper()
|
||||
... print(elem.upper())
|
||||
G
|
||||
H
|
||||
I
|
||||
|
@ -194,7 +194,7 @@ the tasklist if the input stream is not exhausted::
|
|||
... pending.append(task)
|
||||
...
|
||||
>>> for value in roundrobin('abc', 'd', 'efgh'):
|
||||
... print value
|
||||
... print(value)
|
||||
|
||||
a
|
||||
d
|
||||
|
@ -221,7 +221,7 @@ two adjacent nodes into one by grouping them in a list::
|
|||
... d.append(pair)
|
||||
... return list(d)
|
||||
...
|
||||
>>> print maketree('abcdefgh')
|
||||
>>> print(maketree('abcdefgh'))
|
||||
[[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]]
|
||||
|
||||
|
||||
|
@ -386,14 +386,14 @@ Setting the :attr:`default_factory` to :class:`set` makes the
|
|||
import csv
|
||||
EmployeeRecord = NamedTuple('EmployeeRecord', 'name age title department paygrade')
|
||||
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
|
||||
other iterable type, use the star-operator [#]_ to unpack the values::
|
||||
|
||||
>>> Color = NamedTuple('Color', 'name code')
|
||||
>>> m = dict(red=1, green=2, blue=3)
|
||||
>>> print Color(*m.popitem())
|
||||
>>> print(Color(*m.popitem()))
|
||||
Color(name='blue', code=3)
|
||||
|
||||
.. rubric:: Footnotes
|
||||
|
|
|
@ -26,12 +26,12 @@ Functions provided:
|
|||
|
||||
@contextmanager
|
||||
def tag(name):
|
||||
print "<%s>" % name
|
||||
print("<%s>" % name)
|
||||
yield
|
||||
print "</%s>" % name
|
||||
print("</%s>" % name)
|
||||
|
||||
>>> with tag("h1"):
|
||||
... print "foo"
|
||||
... print("foo")
|
||||
...
|
||||
<h1>
|
||||
foo
|
||||
|
@ -104,7 +104,7 @@ Functions provided:
|
|||
|
||||
with closing(urllib.urlopen('http://www.python.org')) as page:
|
||||
for line in page:
|
||||
print line
|
||||
print(line)
|
||||
|
||||
without needing to explicitly close ``page``. Even if an error occurs,
|
||||
``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. ::
|
|||
>>> C = Cookie.SmartCookie()
|
||||
>>> C["fig"] = "newton"
|
||||
>>> C["sugar"] = "wafer"
|
||||
>>> print C # generate HTTP headers
|
||||
>>> print(C) # generate HTTP headers
|
||||
Set-Cookie: sugar=wafer
|
||||
Set-Cookie: fig=newton
|
||||
>>> print C.output() # same thing
|
||||
>>> print(C.output()) # same thing
|
||||
Set-Cookie: sugar=wafer
|
||||
Set-Cookie: fig=newton
|
||||
>>> C = Cookie.SmartCookie()
|
||||
>>> C["rocky"] = "road"
|
||||
>>> C["rocky"]["path"] = "/cookie"
|
||||
>>> print C.output(header="Cookie:")
|
||||
>>> print(C.output(header="Cookie:"))
|
||||
Cookie: rocky=road; Path=/cookie
|
||||
>>> print C.output(attrs=[], header="Cookie:")
|
||||
>>> print(C.output(attrs=[], header="Cookie:"))
|
||||
Cookie: rocky=road
|
||||
>>> C = Cookie.SmartCookie()
|
||||
>>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
|
||||
>>> print C
|
||||
>>> print(C)
|
||||
Set-Cookie: vienna=finger
|
||||
Set-Cookie: chips=ahoy
|
||||
>>> C = Cookie.SmartCookie()
|
||||
>>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
|
||||
>>> print C
|
||||
>>> print(C)
|
||||
Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
|
||||
>>> C = Cookie.SmartCookie()
|
||||
>>> C["oreo"] = "doublestuff"
|
||||
>>> C["oreo"]["path"] = "/"
|
||||
>>> print C
|
||||
>>> print(C)
|
||||
Set-Cookie: oreo=doublestuff; Path=/
|
||||
>>> C = Cookie.SmartCookie()
|
||||
>>> C["twix"] = "none for you"
|
||||
|
@ -252,7 +252,7 @@ The following example demonstrates how to use the :mod:`Cookie` module. ::
|
|||
'7'
|
||||
>>> C["string"].value
|
||||
'seven'
|
||||
>>> print C
|
||||
>>> print(C)
|
||||
Set-Cookie: number=7
|
||||
Set-Cookie: string=seven
|
||||
>>> C = Cookie.SerialCookie()
|
||||
|
@ -262,7 +262,7 @@ The following example demonstrates how to use the :mod:`Cookie` module. ::
|
|||
7
|
||||
>>> C["string"].value
|
||||
'seven'
|
||||
>>> print C
|
||||
>>> print(C)
|
||||
Set-Cookie: number="I7\012."
|
||||
Set-Cookie: string="S'seven'\012p1\012."
|
||||
>>> C = Cookie.SmartCookie()
|
||||
|
@ -272,7 +272,7 @@ The following example demonstrates how to use the :mod:`Cookie` module. ::
|
|||
7
|
||||
>>> C["string"].value
|
||||
'seven'
|
||||
>>> print C
|
||||
>>> print(C)
|
||||
Set-Cookie: number="I7\012."
|
||||
Set-Cookie: string=seven
|
||||
|
||||
|
|
|
@ -390,14 +390,14 @@ The simplest example of reading a CSV file::
|
|||
import csv
|
||||
reader = csv.reader(open("some.csv", "rb"))
|
||||
for row in reader:
|
||||
print row
|
||||
print(row)
|
||||
|
||||
Reading a file with an alternate format::
|
||||
|
||||
import csv
|
||||
reader = csv.reader(open("passwd", "rb"), delimiter=':', quoting=csv.QUOTE_NONE)
|
||||
for row in reader:
|
||||
print row
|
||||
print(row)
|
||||
|
||||
The corresponding simplest possible writing example is::
|
||||
|
||||
|
@ -420,7 +420,7 @@ A slightly more advanced use of the reader --- catching and reporting errors::
|
|||
reader = csv.reader(open(filename, "rb"))
|
||||
try:
|
||||
for row in reader:
|
||||
print row
|
||||
print(row)
|
||||
except csv.Error as e:
|
||||
sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
|
||||
|
||||
|
@ -429,7 +429,7 @@ done::
|
|||
|
||||
import csv
|
||||
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
|
||||
it is 8-bit-clean save for some problems with ASCII NUL characters. So you can
|
||||
|
|
|
@ -48,9 +48,9 @@ library containing most standard C functions, and uses the cdecl calling
|
|||
convention::
|
||||
|
||||
>>> from ctypes import *
|
||||
>>> print windll.kernel32 # doctest: +WINDOWS
|
||||
>>> print(windll.kernel32) # doctest: +WINDOWS
|
||||
<WinDLL 'kernel32', handle ... at ...>
|
||||
>>> print cdll.msvcrt # doctest: +WINDOWS
|
||||
>>> print(cdll.msvcrt) # doctest: +WINDOWS
|
||||
<CDLL 'msvcrt', handle ... at ...>
|
||||
>>> libc = cdll.msvcrt # doctest: +WINDOWS
|
||||
>>>
|
||||
|
@ -82,9 +82,9 @@ Functions are accessed as attributes of dll objects::
|
|||
>>> from ctypes import *
|
||||
>>> libc.printf
|
||||
<_FuncPtr object at 0x...>
|
||||
>>> print windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
|
||||
>>> print(windll.kernel32.GetModuleHandleA) # doctest: +WINDOWS
|
||||
<_FuncPtr object at 0x...>
|
||||
>>> print windll.kernel32.MyOwnFunction # doctest: +WINDOWS
|
||||
>>> print(windll.kernel32.MyOwnFunction) # doctest: +WINDOWS
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in ?
|
||||
File "ctypes.py", line 239, in __getattr__
|
||||
|
@ -145,9 +145,9 @@ handle.
|
|||
This example calls both functions with a NULL pointer (``None`` should be used
|
||||
as the NULL pointer)::
|
||||
|
||||
>>> print libc.time(None) # doctest: +SKIP
|
||||
>>> print(libc.time(None)) # doctest: +SKIP
|
||||
1150640792
|
||||
>>> print hex(windll.kernel32.GetModuleHandleA(None)) # doctest: +WINDOWS
|
||||
>>> print(hex(windll.kernel32.GetModuleHandleA(None))) # doctest: +WINDOWS
|
||||
0x1d000000
|
||||
>>>
|
||||
|
||||
|
@ -269,12 +269,12 @@ the correct type and value::
|
|||
Since these types are mutable, their value can also be changed afterwards::
|
||||
|
||||
>>> i = c_int(42)
|
||||
>>> print i
|
||||
>>> print(i)
|
||||
c_long(42)
|
||||
>>> print i.value
|
||||
>>> print(i.value)
|
||||
42
|
||||
>>> i.value = -99
|
||||
>>> print i.value
|
||||
>>> print(i.value)
|
||||
-99
|
||||
>>>
|
||||
|
||||
|
@ -285,12 +285,12 @@ strings are immutable)::
|
|||
|
||||
>>> s = "Hello, World"
|
||||
>>> c_s = c_char_p(s)
|
||||
>>> print c_s
|
||||
>>> print(c_s)
|
||||
c_char_p('Hello, World')
|
||||
>>> c_s.value = "Hi, there"
|
||||
>>> print c_s
|
||||
>>> print(c_s)
|
||||
c_char_p('Hi, there')
|
||||
>>> print s # first string is unchanged
|
||||
>>> print(s) # first string is unchanged
|
||||
Hello, World
|
||||
>>>
|
||||
|
||||
|
@ -303,18 +303,18 @@ property::
|
|||
|
||||
>>> from ctypes import *
|
||||
>>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes
|
||||
>>> print sizeof(p), repr(p.raw)
|
||||
>>> print(sizeof(p), repr(p.raw))
|
||||
3 '\x00\x00\x00'
|
||||
>>> p = create_string_buffer("Hello") # create a buffer containing a NUL terminated string
|
||||
>>> print sizeof(p), repr(p.raw)
|
||||
>>> print(sizeof(p), repr(p.raw))
|
||||
6 'Hello\x00'
|
||||
>>> print repr(p.value)
|
||||
>>> print(repr(p.value))
|
||||
'Hello'
|
||||
>>> p = create_string_buffer("Hello", 10) # create a 10 byte buffer
|
||||
>>> print sizeof(p), repr(p.raw)
|
||||
>>> print(sizeof(p), repr(p.raw))
|
||||
10 'Hello\x00\x00\x00\x00\x00'
|
||||
>>> p.value = "Hi"
|
||||
>>> print sizeof(p), repr(p.raw)
|
||||
>>> print(sizeof(p), repr(p.raw))
|
||||
10 'Hi\x00lo\x00\x00\x00\x00\x00'
|
||||
>>>
|
||||
|
||||
|
@ -444,7 +444,7 @@ a string pointer and a char, and returns a pointer to a string::
|
|||
>>> strchr.restype = c_char_p # c_char_p is a pointer to a string
|
||||
>>> strchr("abcdef", ord("d"))
|
||||
'def'
|
||||
>>> print strchr("abcdef", ord("x"))
|
||||
>>> print(strchr("abcdef", ord("x")))
|
||||
None
|
||||
>>>
|
||||
|
||||
|
@ -460,7 +460,7 @@ single character Python string into a C char::
|
|||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in ?
|
||||
ArgumentError: argument 2: exceptions.TypeError: one character string expected
|
||||
>>> print strchr("abcdef", "x")
|
||||
>>> print(strchr("abcdef", "x"))
|
||||
None
|
||||
>>> strchr("abcdef", "d")
|
||||
'def'
|
||||
|
@ -516,12 +516,12 @@ object in Python itself::
|
|||
>>> i = c_int()
|
||||
>>> f = c_float()
|
||||
>>> s = create_string_buffer('\000' * 32)
|
||||
>>> print i.value, f.value, repr(s.value)
|
||||
>>> print(i.value, f.value, repr(s.value))
|
||||
0 0.0 ''
|
||||
>>> libc.sscanf("1 3.14 Hello", "%d %f %s",
|
||||
... byref(i), byref(f), s)
|
||||
3
|
||||
>>> print i.value, f.value, repr(s.value)
|
||||
>>> print(i.value, f.value, repr(s.value))
|
||||
1 3.1400001049 'Hello'
|
||||
>>>
|
||||
|
||||
|
@ -549,10 +549,10 @@ constructor::
|
|||
... ("y", c_int)]
|
||||
...
|
||||
>>> point = POINT(10, 20)
|
||||
>>> print point.x, point.y
|
||||
>>> print(point.x, point.y)
|
||||
10 20
|
||||
>>> point = POINT(y=5)
|
||||
>>> print point.x, point.y
|
||||
>>> print(point.x, point.y)
|
||||
0 5
|
||||
>>> POINT(1, 2, 3)
|
||||
Traceback (most recent call last):
|
||||
|
@ -571,9 +571,9 @@ Here is a RECT structure which contains two POINTs named ``upperleft`` and
|
|||
... ("lowerright", POINT)]
|
||||
...
|
||||
>>> rc = RECT(point)
|
||||
>>> print rc.upperleft.x, rc.upperleft.y
|
||||
>>> print(rc.upperleft.x, rc.upperleft.y)
|
||||
0 5
|
||||
>>> print rc.lowerright.x, rc.lowerright.y
|
||||
>>> print(rc.lowerright.x, rc.lowerright.y)
|
||||
0 0
|
||||
>>>
|
||||
|
||||
|
@ -585,9 +585,9 @@ Nested structures can also be initialized in the constructor in several ways::
|
|||
Fields descriptors can be retrieved from the *class*, they are useful for
|
||||
debugging because they can provide useful information::
|
||||
|
||||
>>> print POINT.x
|
||||
>>> print(POINT.x)
|
||||
<Field type=c_long, ofs=0, size=4>
|
||||
>>> print POINT.y
|
||||
>>> print(POINT.y)
|
||||
<Field type=c_long, ofs=4, size=4>
|
||||
>>>
|
||||
|
||||
|
@ -622,9 +622,9 @@ item in the :attr:`_fields_` tuples::
|
|||
... _fields_ = [("first_16", c_int, 16),
|
||||
... ("second_16", c_int, 16)]
|
||||
...
|
||||
>>> print Int.first_16
|
||||
>>> print(Int.first_16)
|
||||
<Field type=c_long, ofs=0:0, bits=16>
|
||||
>>> print Int.second_16
|
||||
>>> print(Int.second_16)
|
||||
<Field type=c_long, ofs=0:16, bits=16>
|
||||
>>>
|
||||
|
||||
|
@ -653,7 +653,7 @@ POINTs among other stuff::
|
|||
... ("b", c_float),
|
||||
... ("point_array", POINT * 4)]
|
||||
>>>
|
||||
>>> print len(MyStruct().point_array)
|
||||
>>> print(len(MyStruct().point_array))
|
||||
4
|
||||
>>>
|
||||
|
||||
|
@ -661,7 +661,7 @@ Instances are created in the usual way, by calling the class::
|
|||
|
||||
arr = TenPointsArrayType()
|
||||
for pt in arr:
|
||||
print pt.x, pt.y
|
||||
print(pt.x, pt.y)
|
||||
|
||||
The above code print a series of ``0 0`` lines, because the array contents is
|
||||
initialized to zeros.
|
||||
|
@ -671,9 +671,9 @@ Initializers of the correct type can also be specified::
|
|||
>>> from ctypes import *
|
||||
>>> TenIntegers = c_int * 10
|
||||
>>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
|
||||
>>> print ii
|
||||
>>> print(ii)
|
||||
<c_long_Array_10 object at 0x...>
|
||||
>>> for i in ii: print i,
|
||||
>>> for i in ii: print(i, end=" ")
|
||||
...
|
||||
1 2 3 4 5 6 7 8 9 10
|
||||
>>>
|
||||
|
@ -725,10 +725,10 @@ Pointer instances can also be indexed with integers::
|
|||
|
||||
Assigning to an integer index changes the pointed to value::
|
||||
|
||||
>>> print i
|
||||
>>> print(i)
|
||||
c_long(99)
|
||||
>>> pi[0] = 22
|
||||
>>> print i
|
||||
>>> print(i)
|
||||
c_long(22)
|
||||
>>>
|
||||
|
||||
|
@ -758,7 +758,7 @@ Calling the pointer type without an argument creates a ``NULL`` pointer.
|
|||
``NULL`` pointers have a ``False`` boolean value::
|
||||
|
||||
>>> null_ptr = POINTER(c_int)()
|
||||
>>> print bool(null_ptr)
|
||||
>>> print(bool(null_ptr))
|
||||
False
|
||||
>>>
|
||||
|
||||
|
@ -797,7 +797,7 @@ pointer types. So, for ``POINTER(c_int)``, ctypes accepts an array of c_int::
|
|||
>>> bar.values = (c_int * 3)(1, 2, 3)
|
||||
>>> bar.count = 3
|
||||
>>> for i in range(bar.count):
|
||||
... print bar.values[i]
|
||||
... print(bar.values[i])
|
||||
...
|
||||
1
|
||||
2
|
||||
|
@ -841,7 +841,7 @@ structure::
|
|||
|
||||
>>> bar = Bar()
|
||||
>>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
|
||||
>>> print bar.values[0]
|
||||
>>> print(bar.values[0])
|
||||
0
|
||||
>>>
|
||||
|
||||
|
@ -898,7 +898,7 @@ other, and finally follow the pointer chain a few times::
|
|||
>>> c2.next = pointer(c1)
|
||||
>>> p = c1
|
||||
>>> for i in range(8):
|
||||
... print p.name,
|
||||
... print(p.name, end=" ")
|
||||
... p = p.next[0]
|
||||
...
|
||||
foo bar foo bar foo bar foo bar
|
||||
|
@ -952,7 +952,7 @@ For the first implementation of the callback function, we simply print the
|
|||
arguments we get, and return 0 (incremental development ;-)::
|
||||
|
||||
>>> def py_cmp_func(a, b):
|
||||
... print "py_cmp_func", a, b
|
||||
... print("py_cmp_func", a, b)
|
||||
... return 0
|
||||
...
|
||||
>>>
|
||||
|
@ -980,7 +980,7 @@ And we're ready to go::
|
|||
We know how to access the contents of a pointer, so lets redefine our callback::
|
||||
|
||||
>>> def py_cmp_func(a, b):
|
||||
... print "py_cmp_func", a[0], b[0]
|
||||
... print("py_cmp_func", a[0], b[0])
|
||||
... return 0
|
||||
...
|
||||
>>> cmp_func = CMPFUNC(py_cmp_func)
|
||||
|
@ -1016,7 +1016,7 @@ Ah, we're nearly done! The last step is to actually compare the two items and
|
|||
return a useful result::
|
||||
|
||||
>>> def py_cmp_func(a, b):
|
||||
... print "py_cmp_func", a[0], b[0]
|
||||
... print("py_cmp_func", a[0], b[0])
|
||||
... return a[0] - b[0]
|
||||
...
|
||||
>>>
|
||||
|
@ -1051,7 +1051,7 @@ more comparisons than the linux version!
|
|||
|
||||
As we can easily check, our array is sorted now::
|
||||
|
||||
>>> for i in ia: print i,
|
||||
>>> for i in ia: print(i, end=" ")
|
||||
...
|
||||
1 5 7 33 99
|
||||
>>>
|
||||
|
@ -1078,7 +1078,7 @@ the type. *pythonapi* is a predefined symbol giving access to the Python C
|
|||
api::
|
||||
|
||||
>>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
|
||||
>>> print opt_flag
|
||||
>>> print(opt_flag)
|
||||
c_long(0)
|
||||
>>>
|
||||
|
||||
|
@ -1121,7 +1121,7 @@ access violation or whatever, so it's better to break out of the loop when we
|
|||
hit the NULL entry::
|
||||
|
||||
>>> for item in table:
|
||||
... print item.name, item.size
|
||||
... print(item.name, item.size)
|
||||
... if item.name is None:
|
||||
... break
|
||||
...
|
||||
|
@ -1156,11 +1156,11 @@ Consider the following example::
|
|||
>>> p1 = POINT(1, 2)
|
||||
>>> p2 = POINT(3, 4)
|
||||
>>> rc = RECT(p1, p2)
|
||||
>>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
|
||||
>>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
|
||||
1 2 3 4
|
||||
>>> # now swap the two points
|
||||
>>> rc.a, rc.b = rc.b, rc.a
|
||||
>>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
|
||||
>>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
|
||||
3 4 3 4
|
||||
>>>
|
||||
|
||||
|
@ -1214,7 +1214,7 @@ smaller than the natural memory block specified by the objects type, a
|
|||
``ValueError`` is raised if this is tried::
|
||||
|
||||
>>> short_array = (c_short * 4)()
|
||||
>>> print sizeof(short_array)
|
||||
>>> print(sizeof(short_array))
|
||||
8
|
||||
>>> resize(short_array, 4)
|
||||
Traceback (most recent call last):
|
||||
|
|
|
@ -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
|
||||
memory that contains them all::
|
||||
|
||||
print db.first()
|
||||
print(db.first())
|
||||
for i in range(1, len(db)):
|
||||
print db.next()
|
||||
print(db.next())
|
||||
|
||||
|
||||
.. method:: dbhash.previous()
|
||||
|
|
|
@ -1052,7 +1052,7 @@ to work with the :class:`Decimal` class::
|
|||
def pi():
|
||||
"""Compute Pi to the current precision.
|
||||
|
||||
>>> print pi()
|
||||
>>> print(pi())
|
||||
3.141592653589793238462643383
|
||||
|
||||
"""
|
||||
|
@ -1071,13 +1071,13 @@ to work with the :class:`Decimal` class::
|
|||
def exp(x):
|
||||
"""Return e raised to the power of x. Result type matches input type.
|
||||
|
||||
>>> print exp(Decimal(1))
|
||||
>>> print(exp(Decimal(1)))
|
||||
2.718281828459045235360287471
|
||||
>>> print exp(Decimal(2))
|
||||
>>> print(exp(Decimal(2)))
|
||||
7.389056098930650227230427461
|
||||
>>> print exp(2.0)
|
||||
>>> print(exp(2.0))
|
||||
7.38905609893
|
||||
>>> print exp(2+0j)
|
||||
>>> print(exp(2+0j))
|
||||
(7.38905609893+0j)
|
||||
|
||||
"""
|
||||
|
@ -1095,11 +1095,11 @@ to work with the :class:`Decimal` class::
|
|||
def cos(x):
|
||||
"""Return the cosine of x as measured in radians.
|
||||
|
||||
>>> print cos(Decimal('0.5'))
|
||||
>>> print(cos(Decimal('0.5')))
|
||||
0.8775825618903727161162815826
|
||||
>>> print cos(0.5)
|
||||
>>> print(cos(0.5))
|
||||
0.87758256189
|
||||
>>> print cos(0.5+0j)
|
||||
>>> print(cos(0.5+0j))
|
||||
(0.87758256189+0j)
|
||||
|
||||
"""
|
||||
|
@ -1118,11 +1118,11 @@ to work with the :class:`Decimal` class::
|
|||
def sin(x):
|
||||
"""Return the sine of x as measured in radians.
|
||||
|
||||
>>> print sin(Decimal('0.5'))
|
||||
>>> print(sin(Decimal('0.5')))
|
||||
0.4794255386042030002732879352
|
||||
>>> print sin(0.5)
|
||||
>>> print(sin(0.5))
|
||||
0.479425538604
|
||||
>>> print sin(0.5+0j)
|
||||
>>> print(sin(0.5+0j))
|
||||
(0.479425538604+0j)
|
||||
|
||||
"""
|
||||
|
|
|
@ -194,7 +194,7 @@
|
|||
|
||||
>>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
|
||||
... 'ore\ntree\nemu\n'.splitlines(1))
|
||||
>>> print ''.join(diff),
|
||||
>>> print(''.join(diff), end="")
|
||||
- one
|
||||
? ^
|
||||
+ ore
|
||||
|
@ -219,11 +219,11 @@
|
|||
>>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
|
||||
... 'ore\ntree\nemu\n'.splitlines(1))
|
||||
>>> diff = list(diff) # materialize the generated delta into a list
|
||||
>>> print ''.join(restore(diff, 1)),
|
||||
>>> print(''.join(restore(diff, 1)), end="")
|
||||
one
|
||||
two
|
||||
three
|
||||
>>> print ''.join(restore(diff, 2)),
|
||||
>>> print(''.join(restore(diff, 2)), end="")
|
||||
ore
|
||||
tree
|
||||
emu
|
||||
|
@ -412,8 +412,8 @@ use :meth:`set_seq2` to set the commonly used sequence once and call
|
|||
>>> b = "abycdf"
|
||||
>>> s = SequenceMatcher(None, a, b)
|
||||
>>> for tag, i1, i2, j1, j2 in s.get_opcodes():
|
||||
... print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
|
||||
... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))
|
||||
... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
|
||||
... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])))
|
||||
delete a[0:1] (q) b[0:0] ()
|
||||
equal a[1:3] (ab) b[0:2] (ab)
|
||||
replace a[3:4] (x) b[2:3] (y)
|
||||
|
@ -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 are close matches::
|
||||
|
||||
>>> print round(s.ratio(), 3)
|
||||
>>> print(round(s.ratio(), 3))
|
||||
0.866
|
||||
|
||||
If you're only interested in where the sequences match,
|
||||
:meth:`get_matching_blocks` is handy::
|
||||
|
||||
>>> 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[8] and b[17] match for 6 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
|
|||
:meth:`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]
|
||||
insert a[8:8] b[8:17]
|
||||
equal a[8:14] b[17:23]
|
||||
|
|
|
@ -309,11 +309,11 @@ your own :class:`DocTestParser` class.
|
|||
>>> x
|
||||
12
|
||||
>>> if x == 13:
|
||||
... print "yes"
|
||||
... print("yes")
|
||||
... else:
|
||||
... print "no"
|
||||
... print "NO"
|
||||
... print "NO!!!"
|
||||
... print("no")
|
||||
... print("NO")
|
||||
... print("NO!!!")
|
||||
...
|
||||
no
|
||||
NO
|
||||
|
@ -340,7 +340,7 @@ The fine print:
|
|||
|
||||
>>> def f(x):
|
||||
... r'''Backslashes in a raw docstring: m\n'''
|
||||
>>> print f.__doc__
|
||||
>>> print(f.__doc__)
|
||||
Backslashes in a raw docstring: m\n
|
||||
|
||||
Otherwise, the backslash will be interpreted as part of the string. For example,
|
||||
|
@ -349,7 +349,7 @@ The fine print:
|
|||
|
||||
>>> def f(x):
|
||||
... '''Backslashes in a raw docstring: m\\n'''
|
||||
>>> print f.__doc__
|
||||
>>> print(f.__doc__)
|
||||
Backslashes in a raw docstring: m\n
|
||||
|
||||
* The starting column doesn't matter::
|
||||
|
@ -639,7 +639,7 @@ example. Use ``+`` to enable the named behavior, or ``-`` to disable it.
|
|||
|
||||
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,
|
||||
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
|
|||
is on a single line. This test also passes, and also requires a directive to do
|
||||
so::
|
||||
|
||||
>>> print range(20) # doctest: +ELLIPSIS
|
||||
>>> print(range(20)) # doctest: +ELLIPSIS
|
||||
[0, 1, ..., 18, 19]
|
||||
|
||||
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]
|
||||
|
||||
If multiple directive comments are used for a single example, then they are
|
||||
combined::
|
||||
|
||||
>>> print range(20) # doctest: +ELLIPSIS
|
||||
>>> print(range(20)) # doctest: +ELLIPSIS
|
||||
... # doctest: +NORMALIZE_WHITESPACE
|
||||
[0, 1, ..., 18, 19]
|
||||
|
||||
|
@ -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
|
||||
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
|
||||
[0, ..., 4, 10, ..., 19, 30, ..., 39, 50, ..., 59]
|
||||
|
||||
|
@ -746,9 +746,9 @@ and C libraries vary widely in quality here. ::
|
|||
|
||||
>>> 1./7 # risky
|
||||
0.14285714285714285
|
||||
>>> print 1./7 # safer
|
||||
>>> print(1./7) # safer
|
||||
0.142857142857
|
||||
>>> print round(1./7, 6) # much safer
|
||||
>>> print(round(1./7, 6)) # much safer
|
||||
0.142857
|
||||
|
||||
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:
|
|||
>>> def f(x):
|
||||
... g(x*2)
|
||||
>>> def g(x):
|
||||
... print x+3
|
||||
... print(x+3)
|
||||
... import pdb; pdb.set_trace()
|
||||
>>> f(3)
|
||||
9
|
||||
|
@ -1533,10 +1533,10 @@ Doctest provides several mechanisms for debugging doctest examples:
|
|||
-> import pdb; pdb.set_trace()
|
||||
(Pdb) list
|
||||
1 def g(x):
|
||||
2 print x+3
|
||||
2 print(x+3)
|
||||
3 -> import pdb; pdb.set_trace()
|
||||
[EOF]
|
||||
(Pdb) print x
|
||||
(Pdb) p x
|
||||
6
|
||||
(Pdb) step
|
||||
--Return--
|
||||
|
@ -1546,7 +1546,7 @@ Doctest provides several mechanisms for debugging doctest examples:
|
|||
1 def f(x):
|
||||
2 -> g(x*2)
|
||||
[EOF]
|
||||
(Pdb) print x
|
||||
(Pdb) p x
|
||||
3
|
||||
(Pdb) step
|
||||
--Return--
|
||||
|
@ -1571,14 +1571,14 @@ code under the debugger:
|
|||
returned as a string. For example, ::
|
||||
|
||||
import doctest
|
||||
print doctest.script_from_examples(r"""
|
||||
print(doctest.script_from_examples(r"""
|
||||
Set x and y to 1 and 2.
|
||||
>>> x, y = 1, 2
|
||||
|
||||
Print their sum:
|
||||
>>> print x+y
|
||||
>>> print(x+y)
|
||||
3
|
||||
""")
|
||||
"""))
|
||||
|
||||
displays::
|
||||
|
||||
|
@ -1586,7 +1586,7 @@ code under the debugger:
|
|||
x, y = 1, 2
|
||||
#
|
||||
# Print their sum:
|
||||
print x+y
|
||||
print(x+y)
|
||||
# Expected:
|
||||
## 3
|
||||
|
||||
|
@ -1607,7 +1607,7 @@ code under the debugger:
|
|||
contains a top-level function :func:`f`, then ::
|
||||
|
||||
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
|
||||
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
|
|||
|
||||
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
|
||||
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
|
||||
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:
|
|||
|
||||
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` 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
|
||||
``str(aMessage)``, a.k.a. :meth:`Message.__str__`, which simplify the generation
|
||||
|
|
|
@ -31,7 +31,7 @@ example::
|
|||
>>> msg = Message()
|
||||
>>> h = Header('p\xf6stal', 'iso-8859-1')
|
||||
>>> msg['Subject'] = h
|
||||
>>> print msg.as_string()
|
||||
>>> print(msg.as_string())
|
||||
Subject: =?iso-8859-1?q?p=F6stal?=
|
||||
|
||||
|
||||
|
|
|
@ -60,6 +60,6 @@ The following function has been added as a useful debugging tool. It should
|
|||
text/plain
|
||||
text/plain
|
||||
|
||||
Optional *fp* is a file-like object to print the output to. It must be suitable
|
||||
for Python's extended print statement. *level* is used internally.
|
||||
Optional *fp* is a file-like object to print the output to. It must be
|
||||
suitable for Python's :func:`print` function. *level* is used internally.
|
||||
|
||||
|
|
|
@ -167,7 +167,7 @@ included in the mapping interface.
|
|||
the ``in`` operator, e.g.::
|
||||
|
||||
if 'message-id' in myMessage:
|
||||
print 'Message-ID:', myMessage['message-id']
|
||||
print('Message-ID:', myMessage['message-id'])
|
||||
|
||||
|
||||
.. method:: Message.__getitem__(name)
|
||||
|
@ -458,7 +458,7 @@ Here are some additional useful methods:
|
|||
structure::
|
||||
|
||||
>>> for part in msg.walk():
|
||||
... print part.get_content_type()
|
||||
... print(part.get_content_type())
|
||||
multipart/report
|
||||
text/plain
|
||||
message/delivery-status
|
||||
|
|
|
@ -51,7 +51,7 @@ patterns.
|
|||
|
||||
for file in os.listdir('.'):
|
||||
if fnmatch.fnmatch(file, '*.txt'):
|
||||
print file
|
||||
print(file)
|
||||
|
||||
|
||||
.. function:: fnmatchcase(filename, pattern)
|
||||
|
@ -78,7 +78,7 @@ patterns.
|
|||
>>> regex
|
||||
'.*\\.txt$'
|
||||
>>> reobj = re.compile(regex)
|
||||
>>> print reobj.match('foobar.txt')
|
||||
>>> print(reobj.match('foobar.txt'))
|
||||
<_sre.SRE_Match object at 0x...>
|
||||
|
||||
|
||||
|
|
|
@ -325,7 +325,7 @@ available. They are listed here in alphabetical order.
|
|||
``(1, seq[1])``, ``(2, seq[2])``, .... For example::
|
||||
|
||||
>>> for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter')]:
|
||||
>>> print i, season
|
||||
>>> print(i, season)
|
||||
0 Spring
|
||||
1 Summer
|
||||
2 Fall
|
||||
|
@ -350,7 +350,7 @@ available. They are listed here in alphabetical order.
|
|||
the evaluated expression. Syntax errors are reported as exceptions. Example::
|
||||
|
||||
>>> x = 1
|
||||
>>> print eval('x+1')
|
||||
>>> eval('x+1')
|
||||
2
|
||||
|
||||
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:
|
|||
>>> def my_decorator(f):
|
||||
... @wraps(f)
|
||||
... def wrapper(*args, **kwds):
|
||||
... print 'Calling decorated function'
|
||||
... print('Calling decorated function')
|
||||
... return f(*args, **kwds)
|
||||
... return wrapper
|
||||
...
|
||||
>>> @my_decorator
|
||||
... def example():
|
||||
... """Docstring"""
|
||||
... print 'Called example function'
|
||||
... print('Called example function')
|
||||
...
|
||||
>>> example()
|
||||
Calling decorated function
|
||||
|
|
|
@ -93,7 +93,7 @@ methods:
|
|||
|
||||
k = db.firstkey()
|
||||
while k != None:
|
||||
print k
|
||||
print(k)
|
||||
k = db.nextkey(k)
|
||||
|
||||
|
||||
|
|
|
@ -112,7 +112,7 @@ In a script, typical usage is something like this::
|
|||
opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
|
||||
except getopt.GetoptError as err:
|
||||
# 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()
|
||||
sys.exit(2)
|
||||
output = None
|
||||
|
|
|
@ -126,7 +126,7 @@ Here's an example of typical usage for this API::
|
|||
gettext.textdomain('myapplication')
|
||||
_ = gettext.gettext
|
||||
# ...
|
||||
print _('This is a translatable string.')
|
||||
print(_('This is a translatable string.'))
|
||||
|
||||
|
||||
Class-based API
|
||||
|
@ -201,7 +201,7 @@ the built-in namespace as the function :func:`_`.
|
|||
candidates for translation, by wrapping them in a call to the :func:`_`
|
||||
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
|
||||
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::
|
|||
import gettext
|
||||
cat = gettext.Catalog(domain, localedir)
|
||||
_ = cat.gettext
|
||||
print _('hello world')
|
||||
print(_('hello world'))
|
||||
|
||||
For compatibility with this older module, the function :func:`Catalog` is an
|
||||
alias for the :func:`translation` function described above.
|
||||
|
@ -604,7 +604,7 @@ translation until later. A classic example is::
|
|||
]
|
||||
# ...
|
||||
for a in animals:
|
||||
print a
|
||||
print(a)
|
||||
|
||||
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
|
||||
|
@ -625,7 +625,7 @@ Here is one way you can handle this situation::
|
|||
|
||||
# ...
|
||||
for a in animals:
|
||||
print _(a)
|
||||
print(_(a))
|
||||
|
||||
This works because the dummy definition of :func:`_` simply returns the string
|
||||
unchanged. And this dummy definition will temporarily override any definition
|
||||
|
@ -649,7 +649,7 @@ Another way to handle this is with the following example::
|
|||
|
||||
# ...
|
||||
for a in animals:
|
||||
print _(a)
|
||||
print(_(a))
|
||||
|
||||
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
|
||||
|
|
|
@ -77,10 +77,10 @@ Example of use::
|
|||
>>> while heap:
|
||||
... ordered.append(heappop(heap))
|
||||
...
|
||||
>>> print ordered
|
||||
>>> ordered
|
||||
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||
>>> data.sort()
|
||||
>>> print data == ordered
|
||||
>>> data == ordered
|
||||
True
|
||||
>>>
|
||||
|
||||
|
|
|
@ -171,8 +171,8 @@ As a basic example, below is a very basic HTML parser that uses the
|
|||
class MyHTMLParser(HTMLParser):
|
||||
|
||||
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):
|
||||
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::
|
|||
>>> conn = httplib.HTTPConnection("www.python.org")
|
||||
>>> conn.request("GET", "/index.html")
|
||||
>>> r1 = conn.getresponse()
|
||||
>>> print r1.status, r1.reason
|
||||
>>> print(r1.status, r1.reason)
|
||||
200 OK
|
||||
>>> data1 = r1.read()
|
||||
>>> conn.request("GET", "/parrot.spam")
|
||||
>>> r2 = conn.getresponse()
|
||||
>>> print r2.status, r2.reason
|
||||
>>> print(r2.status, r2.reason)
|
||||
404 Not Found
|
||||
>>> data2 = r2.read()
|
||||
>>> conn.close()
|
||||
|
@ -494,7 +494,7 @@ Here is an example session that shows how to ``POST`` requests::
|
|||
>>> conn = httplib.HTTPConnection("musi-cal.mojam.com:80")
|
||||
>>> conn.request("POST", "/cgi-bin/query", params, headers)
|
||||
>>> response = conn.getresponse()
|
||||
>>> print response.status, response.reason
|
||||
>>> print(response.status, response.reason)
|
||||
200 OK
|
||||
>>> data = response.read()
|
||||
>>> conn.close()
|
||||
|
|
|
@ -511,7 +511,7 @@ retrieves and prints all messages::
|
|||
typ, data = M.search(None, 'ALL')
|
||||
for num in data[0].split():
|
||||
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.logout()
|
||||
|
||||
|
|
|
@ -385,7 +385,7 @@ can be combined. ::
|
|||
|
||||
>>> amounts = [120.15, 764.05, 823.14]
|
||||
>>> 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 1201 is for $764.05
|
||||
|
@ -393,7 +393,7 @@ can be combined. ::
|
|||
|
||||
>>> import operator
|
||||
>>> for cube in imap(operator.pow, range(1,5), repeat(3)):
|
||||
... print cube
|
||||
... print(cube)
|
||||
...
|
||||
1
|
||||
8
|
||||
|
@ -403,7 +403,7 @@ can be combined. ::
|
|||
>>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura',
|
||||
... '', 'martin', '', 'walter', '', 'mark']
|
||||
>>> for name in islice(reportlines, 3, None, 2):
|
||||
... print name.title()
|
||||
... print(name.title())
|
||||
...
|
||||
Alex
|
||||
Laura
|
||||
|
@ -416,7 +416,7 @@ can be combined. ::
|
|||
>>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
|
||||
>>> di = sorted(d.iteritems(), 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']
|
||||
2 ['b', 'd', 'f']
|
||||
|
@ -427,7 +427,7 @@ can be combined. ::
|
|||
# same group.
|
||||
>>> 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]):
|
||||
... print map(operator.itemgetter(1), g)
|
||||
... print(map(operator.itemgetter(1), g))
|
||||
...
|
||||
[1]
|
||||
[4, 5, 6]
|
||||
|
|
|
@ -841,7 +841,7 @@ module. Here is a basic working example::
|
|||
logging.basicConfig(
|
||||
format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
|
||||
tcpserver = LogRecordSocketReceiver()
|
||||
print "About to start TCP server..."
|
||||
print("About to start TCP server...")
|
||||
tcpserver.serve_until_stopped()
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
@ -31,7 +31,7 @@ In Python, the following code fragment will do the same::
|
|||
import 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
|
||||
suites, plus packages that interface to a small number of common applications.
|
||||
|
|
|
@ -1620,7 +1620,7 @@ interesting::
|
|||
for message in mailbox.mbox('~/mbox'):
|
||||
subject = message['subject'] # Could possibly be None.
|
||||
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
|
||||
format-specific information that can be converted::
|
||||
|
|
|
@ -20,10 +20,10 @@ about a newsgroup and print the subjects of the last 10 articles::
|
|||
|
||||
>>> s = NNTP('news.cwi.nl')
|
||||
>>> 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
|
||||
>>> 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...
|
||||
3793 Re: Who likes Info files?
|
||||
|
|
|
@ -348,7 +348,7 @@ right up against the option: since ``"-n42"`` (one argument) is equivalent to
|
|||
``"-n 42"`` (two arguments), the code ::
|
||||
|
||||
(options, args) = parser.parse_args(["-n42"])
|
||||
print options.num
|
||||
print(options.num)
|
||||
|
||||
will print ``"42"``.
|
||||
|
||||
|
@ -646,7 +646,7 @@ Here's what :mod:`optparse`\ -based scripts usually look like::
|
|||
if len(args) != 1:
|
||||
parser.error("incorrect number of arguments")
|
||||
if options.verbose:
|
||||
print "reading %s..." % options.filename
|
||||
print("reading %s..." % options.filename)
|
||||
[...]
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
@ -1215,9 +1215,9 @@ Files and Directories
|
|||
import os
|
||||
from os.path import join, getsize
|
||||
for root, dirs, files in os.walk('python/Lib/email'):
|
||||
print root, "consumes",
|
||||
print sum(getsize(join(root, name)) for name in files),
|
||||
print "bytes in", len(files), "non-directory files"
|
||||
print(root, "consumes", end=" ")
|
||||
print(sum(getsize(join(root, name)) for name in files), end=" ")
|
||||
print("bytes in", len(files), "non-directory files")
|
||||
if 'CVS' in dirs:
|
||||
dirs.remove('CVS') # don't visit CVS directories
|
||||
|
||||
|
|
|
@ -574,11 +574,11 @@ Here's a silly example that *might* shed more light::
|
|||
return 'My name is integer %d' % self.x
|
||||
|
||||
i = Integer(7)
|
||||
print i
|
||||
print(i)
|
||||
p.dump(i)
|
||||
|
||||
datastream = src.getvalue()
|
||||
print repr(datastream)
|
||||
print(repr(datastream))
|
||||
dst = StringIO(datastream)
|
||||
|
||||
up = pickle.Unpickler(dst)
|
||||
|
@ -597,7 +597,7 @@ Here's a silly example that *might* shed more light::
|
|||
up.persistent_load = persistent_load
|
||||
|
||||
j = up.load()
|
||||
print j
|
||||
print(j)
|
||||
|
||||
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
|
||||
|
|
|
@ -191,7 +191,7 @@ retrieves and prints all messages::
|
|||
numMessages = len(M.list()[1])
|
||||
for i in range(numMessages):
|
||||
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
|
||||
example of usage.
|
||||
|
|
|
@ -85,9 +85,10 @@ The :class:`PrettyPrinter` class supports several derivative functions:
|
|||
.. function:: pprint(object[, stream[, indent[, width[, depth]]]])
|
||||
|
||||
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
|
||||
the interactive interpreter instead of a :keyword:`print` statement for
|
||||
inspecting values. *indent*, *width* and *depth* will be passed to the
|
||||
newline. If *stream* is omitted, ``sys.stdout`` is used. This may be used
|
||||
in the interactive interpreter instead of the :func:`print` function for
|
||||
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. ::
|
||||
|
||||
>>> stuff = sys.path[:]
|
||||
|
|
|
@ -577,7 +577,7 @@ discussion in section Limitations above). ::
|
|||
import profile
|
||||
pr = profile.Profile()
|
||||
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
|
||||
and again under the profiler, measuring the time for both. It then computes the
|
||||
|
|
|
@ -494,11 +494,11 @@ arguments. ::
|
|||
|
||||
# 3 handler functions
|
||||
def start_element(name, attrs):
|
||||
print 'Start element:', name, attrs
|
||||
print('Start element:', name, attrs)
|
||||
def end_element(name):
|
||||
print 'End element:', name
|
||||
print('End element:', name)
|
||||
def char_data(data):
|
||||
print 'Character data:', repr(data)
|
||||
print('Character data:', repr(data))
|
||||
|
||||
p = xml.parsers.expat.ParserCreate()
|
||||
|
||||
|
|
|
@ -129,5 +129,5 @@ for file objects could be added::
|
|||
return `obj`
|
||||
|
||||
aRepr = MyRepr()
|
||||
print aRepr.repr(sys.stdin) # prints '<stdin>'
|
||||
print(aRepr.repr(sys.stdin)) # prints '<stdin>'
|
||||
|
||||
|
|
|
@ -33,7 +33,7 @@ automatic :kbd:`Tab` completion::
|
|||
try:
|
||||
import readline
|
||||
except ImportError:
|
||||
print "Module readline not available."
|
||||
print("Module readline not available.")
|
||||
else:
|
||||
import rlcompleter
|
||||
readline.parse_and_bind("tab: complete")
|
||||
|
|
|
@ -30,14 +30,14 @@ Example::
|
|||
|
||||
>>> import sched, time
|
||||
>>> 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():
|
||||
... print time.time()
|
||||
... print(time.time())
|
||||
... s.enter(5, 1, print_time, ())
|
||||
... s.enter(10, 1, print_time, ())
|
||||
... s.run()
|
||||
... print time.time()
|
||||
... print(time.time())
|
||||
...
|
||||
>>> print_some_times()
|
||||
930343690.257
|
||||
|
|
|
@ -143,7 +143,7 @@ be sent, and the handler raises an exception. ::
|
|||
import signal, os
|
||||
|
||||
def handler(signum, frame):
|
||||
print 'Signal handler called with signal', signum
|
||||
print('Signal handler called with signal', signum)
|
||||
raise IOError("Couldn't open device!")
|
||||
|
||||
# Set the signal handler and a 5-second alarm
|
||||
|
|
|
@ -143,12 +143,12 @@ server::
|
|||
import xmlrpclib
|
||||
|
||||
s = xmlrpclib.Server('http://localhost:8000')
|
||||
print s.pow(2,3) # Returns 2**3 = 8
|
||||
print s.add(2,3) # Returns 5
|
||||
print s.div(5,2) # Returns 5//2 = 2
|
||||
print(s.pow(2,3)) # Returns 2**3 = 8
|
||||
print(s.add(2,3)) # Returns 5
|
||||
print(s.div(5,2)) # Returns 5//2 = 2
|
||||
|
||||
# Print list of available methods
|
||||
print s.system.listMethods()
|
||||
print(s.system.listMethods())
|
||||
|
||||
|
||||
CGIXMLRPCRequestHandler
|
||||
|
|
|
@ -317,7 +317,7 @@ example doesn't do any processing of the :rfc:`822` headers. In particular, the
|
|||
|
||||
fromaddr = prompt("From: ")
|
||||
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!
|
||||
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
|
|||
break
|
||||
msg = msg + line
|
||||
|
||||
print "Message length is " + repr(len(msg))
|
||||
print("Message length is", len(msg))
|
||||
|
||||
server = smtplib.SMTP('localhost')
|
||||
server.set_debuglevel(1)
|
||||
|
|
|
@ -730,7 +730,7 @@ The first two examples support IPv4 only. ::
|
|||
s.bind((HOST, PORT))
|
||||
s.listen(1)
|
||||
conn, addr = s.accept()
|
||||
print 'Connected by', addr
|
||||
print('Connected by', addr)
|
||||
while 1:
|
||||
data = conn.recv(1024)
|
||||
if not data: break
|
||||
|
@ -749,7 +749,7 @@ The first two examples support IPv4 only. ::
|
|||
s.send('Hello, world')
|
||||
data = s.recv(1024)
|
||||
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
|
||||
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. ::
|
|||
continue
|
||||
break
|
||||
if s is None:
|
||||
print 'could not open socket'
|
||||
print('could not open socket')
|
||||
sys.exit(1)
|
||||
conn, addr = s.accept()
|
||||
print 'Connected by', addr
|
||||
print('Connected by', addr)
|
||||
while 1:
|
||||
data = conn.recv(1024)
|
||||
if not data: break
|
||||
|
@ -815,10 +815,10 @@ sends traffic to the first one connected successfully. ::
|
|||
continue
|
||||
break
|
||||
if s is None:
|
||||
print 'could not open socket'
|
||||
print('could not open socket')
|
||||
sys.exit(1)
|
||||
s.send('Hello, world')
|
||||
data = s.recv(1024)
|
||||
s.close()
|
||||
print 'Received', repr(data)
|
||||
print('Received', repr(data))
|
||||
|
||||
|
|
|
@ -79,7 +79,7 @@ This example uses the iterator form::
|
|||
>>> c = conn.cursor()
|
||||
>>> c.execute('select * from stocks order by price')
|
||||
>>> for row in c:
|
||||
... print row
|
||||
... print(row)
|
||||
...
|
||||
(u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)
|
||||
(u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
|
||||
|
|
|
@ -297,8 +297,8 @@ sends some bytes, and reads part of the response::
|
|||
|
||||
ssl_sock.connect(('www.verisign.com', 443))
|
||||
|
||||
print repr(ssl_sock.getpeername())
|
||||
print pprint.pformat(ssl_sock.getpeercert())
|
||||
print(repr(ssl_sock.getpeername()))
|
||||
pprint.pprint(ssl_sock.getpeercert())
|
||||
|
||||
# Set a simple HTTP request -- use httplib in actual code.
|
||||
ssl_sock.write("""GET / HTTP/1.0\r
|
||||
|
|
|
@ -22,8 +22,6 @@ interpreter.
|
|||
The principal built-in types are numerics, sequences, mappings, files, classes,
|
||||
instances and exceptions.
|
||||
|
||||
.. index:: statement: print
|
||||
|
||||
Some operations are supported by several object types; in particular,
|
||||
practically all objects can be compared, tested for truth value, and converted
|
||||
to a string (with the :func:`repr` function or the slightly different
|
||||
|
@ -1976,7 +1974,7 @@ Files have the following methods:
|
|||
|
||||
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
|
||||
: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
|
||||
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
|
||||
|
@ -2133,23 +2131,6 @@ the particular object.
|
|||
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:
|
||||
|
||||
Context Manager Types
|
||||
|
|
|
@ -495,7 +495,7 @@ always available.
|
|||
|
||||
File objects corresponding to the interpreter's standard input, output and error
|
||||
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
|
||||
``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
|
||||
|
|
|
@ -26,9 +26,9 @@ described below.
|
|||
|
||||
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`
|
||||
files along the way. If *file_or_dir* is an ordinary Python source file, it is
|
||||
checked for whitespace related problems. The diagnostic messages are written to
|
||||
standard output using the print statement.
|
||||
files along the way. If *file_or_dir* is an ordinary Python source file, it
|
||||
is checked for whitespace related problems. The diagnostic messages are
|
||||
written to standard output using the :func:`print` function.
|
||||
|
||||
|
||||
.. data:: verbose
|
||||
|
|
|
@ -90,9 +90,9 @@ objects::
|
|||
"""Substitute Decimals for floats in a string of statements.
|
||||
|
||||
>>> from decimal import Decimal
|
||||
>>> s = 'print +21.3e-5*-.1234/81.7'
|
||||
>>> s = 'print(+21.3e-5*-.1234/81.7)'
|
||||
>>> decistmt(s)
|
||||
"print +Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7')"
|
||||
"print(+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7'))"
|
||||
|
||||
>>> exec(s)
|
||||
-3.21716034272e-007
|
||||
|
|
|
@ -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
|
||||
: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
|
||||
that in the following example, either all or none of the :keyword:`print`
|
||||
statements are executed::
|
||||
that in the following example, either all or none of the :func:`print` calls are
|
||||
executed::
|
||||
|
||||
if x < y < z: print x; print y; print z
|
||||
if x < y < z: print(x); print(y); print(z)
|
||||
|
||||
Summarizing:
|
||||
|
||||
|
|
|
@ -376,7 +376,7 @@ Here is a simple example that demonstrates the behavior of generators and
|
|||
generator functions::
|
||||
|
||||
>>> 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:
|
||||
... while True:
|
||||
... try:
|
||||
|
@ -387,15 +387,15 @@ generator functions::
|
|||
... except Exception, e:
|
||||
... value = e
|
||||
... 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)
|
||||
>>> print generator.next()
|
||||
>>> print(generator.next())
|
||||
Execution starts when 'next()' is called for the first time.
|
||||
1
|
||||
>>> print generator.next()
|
||||
>>> print(generator.next())
|
||||
None
|
||||
>>> print generator.send(2)
|
||||
>>> print(generator.send(2))
|
||||
2
|
||||
>>> generator.throw(TypeError, "spam")
|
||||
TypeError('spam',)
|
||||
|
@ -640,7 +640,7 @@ A consequence of this is that although the ``*expression`` syntax appears
|
|||
(and the ``**expression`` argument, if any -- see below). So::
|
||||
|
||||
>>> def f(a, b):
|
||||
... print a, b
|
||||
... print(a, b)
|
||||
...
|
||||
>>> f(b=1, *(2,))
|
||||
2 1
|
||||
|
|
|
@ -254,7 +254,7 @@ are not safe! For instance, the following program prints ``[0, 2]``::
|
|||
x = [0, 1]
|
||||
i = 0
|
||||
i, x[i] = 1, 2
|
||||
print x
|
||||
print(x)
|
||||
|
||||
|
||||
.. _augassign:
|
||||
|
|
|
@ -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 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
|
||||
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
|
||||
know where to look in case the input came from a script.
|
||||
|
||||
|
@ -181,8 +181,8 @@ desired. ::
|
|||
... print(inst.args) # arguments stored in .args
|
||||
... print(inst) # __str__ allows args to be printed directly
|
||||
... x, y = inst # __getitem__ allows args to be unpacked directly
|
||||
... print 'x =', x
|
||||
... print 'y =', y
|
||||
... print('x =', x)
|
||||
... print('y =', y)
|
||||
...
|
||||
<type 'Exception'>
|
||||
('spam', 'eggs')
|
||||
|
@ -260,7 +260,7 @@ directly or indirectly. For example::
|
|||
>>> try:
|
||||
... raise MyError(2*2)
|
||||
... except MyError as e:
|
||||
... print 'My exception occurred, value:', e.value
|
||||
... print('My exception occurred, value:', e.value)
|
||||
...
|
||||
My exception occurred, value: 4
|
||||
>>> raise MyError, 'oops!'
|
||||
|
|
|
@ -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
|
||||
reproduce *x*, but the output may be more pleasant to look at::
|
||||
|
||||
>>> print str(0.1)
|
||||
>>> print(str(0.1))
|
||||
0.1
|
||||
|
||||
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::
|
|||
Using the ``%`` operator looks like this::
|
||||
|
||||
>>> 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.
|
||||
|
||||
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::
|
|||
|
||||
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
|
||||
>>> for name, phone in table.items():
|
||||
... print '%-10s ==> %10d' % (name, phone)
|
||||
... print('%-10s ==> %10d' % (name, phone))
|
||||
...
|
||||
Jack ==> 4098
|
||||
Dcab ==> 7678
|
||||
|
@ -159,7 +159,7 @@ instead of by position. This can be done by using form ``%(name)format``, as
|
|||
shown here::
|
||||
|
||||
>>> 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
|
||||
|
||||
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::
|
|||
|
||||
>>> the_world_is_flat = 1
|
||||
>>> 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!
|
||||
|
||||
|
@ -170,6 +170,8 @@ The script can be given an executable mode, or permission, using the
|
|||
Source Code Encoding
|
||||
--------------------
|
||||
|
||||
.. XXX out of date!
|
||||
|
||||
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 ``#!``
|
||||
line to define the source file encoding::
|
||||
|
@ -191,7 +193,7 @@ to the Euro symbol) and then exit::
|
|||
# -*- coding: iso-8859-15 -*-
|
||||
|
||||
currency = u"€"
|
||||
print ord(currency)
|
||||
print(ord(currency))
|
||||
|
||||
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
|
||||
|
|
|
@ -44,7 +44,7 @@ width::
|
|||
... a list of strings instead of one big string with newlines to separate
|
||||
... the wrapped lines."""
|
||||
...
|
||||
>>> print textwrap.fill(doc, width=40)
|
||||
>>> print(textwrap.fill(doc, width=40))
|
||||
The wrap() method is just like fill()
|
||||
except that it returns a list of strings
|
||||
instead of one big string with newlines
|
||||
|
@ -121,7 +121,7 @@ placeholders such as the current date, image sequence number, or file format::
|
|||
>>> for i, filename in enumerate(photofiles):
|
||||
... base, ext = os.path.splitext(filename)
|
||||
... 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_1076.jpg --> Ashley_1.jpg
|
||||
|
@ -155,7 +155,7 @@ and ``"L"`` representing two and four byte unsigned numbers respectively)::
|
|||
filename = data[start:start+filenamesize]
|
||||
start += filenamesize
|
||||
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
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue