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)
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.
{
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;
}
: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
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.
>>> 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
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
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
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()
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
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
>>> L = [1,2,3]
>>> it = iter(L)
- >>> print it
+ >>> it
<iterator object at 0x8116870>
>>> it.next()
1
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::
>>> 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
S = set((2, 3, 5, 7, 11, 13))
for i in S:
- print i
+ print(i)
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
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
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')
for elem in slice[:-1]:
sys.stdout.write(str(elem))
sys.stdout.write(', ')
- print elem[-1]
+ print(elem[-1])
****************************
- Regular Expression HOWTO
+ Regular Expression HOWTO
****************************
:Author: A.M. Kuchling
>>> 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
: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
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
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'
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::
>>> iterator
<callable-iterator object at 0x401833ac>
>>> for match in iterator:
- ... print match.span()
+ ... print(match.span())
...
(0, 2)
(22, 24)
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>
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
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,
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.
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,
``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
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 ``.*``
>>> 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
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.
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
=======================
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.
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.
>>> 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
>>> 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'
>>> 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
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
--------------------------------------
>>> 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,
#!/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
#!/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
------------------
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::
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::
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
f.close()
import os
- print os.listdir('.')
- print os.listdir(u'.')
+ print(os.listdir('.'))
+ print(os.listdir(u'.'))
will produce the following output::
the Unicode versions.
-
+
Tips for Writing Unicode-aware Programs
---------------------------------------
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 ``'/'``
.. comment Describe obscure -U switch somewhere?
.. comment Describe use of codecs.StreamRecoder and StreamReaderWriter
-.. comment
+.. comment
Original outline:
- [ ] Unicode introduction
>>> 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
>>> req = urllib2.Request('http://www.pretend_server.org')
>>> try: urllib2.urlopen(req)
>>> except URLError, e:
- >>> print e.reason
+ >>> print(e.reason)
>>>
(4, 'getaddrinfo failed')
>>> 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"
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
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
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).
# 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).
self.close()
def handle_read(self):
- print self.recv(8192)
+ print(self.recv(8192))
def writable(self):
return (len(self.buffer) > 0)
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')
@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.
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)
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:
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
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
>>> 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
... pending.append(task)
...
>>> for value in roundrobin('abc', 'd', 'efgh'):
- ... print value
+ ... print(value)
a
d
... d.append(pair)
... return list(d)
...
- >>> print maketree('abcdefgh')
+ >>> print(maketree('abcdefgh'))
[[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]]
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
@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
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.
>>> 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"
'7'
>>> C["string"].value
'seven'
- >>> print C
+ >>> print(C)
Set-Cookie: number=7
Set-Cookie: string=seven
>>> C = Cookie.SerialCookie()
7
>>> C["string"].value
'seven'
- >>> print C
+ >>> print(C)
Set-Cookie: number="I7\012."
Set-Cookie: string="S'seven'\012p1\012."
>>> C = Cookie.SmartCookie()
7
>>> C["string"].value
'seven'
- >>> print C
+ >>> print(C)
Set-Cookie: number="I7\012."
Set-Cookie: string=seven
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::
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))
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
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
>>>
>>> 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__
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
>>>
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
>>>
>>> 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
>>>
>>> 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'
>>>
>>> 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
>>>
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'
>>> 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'
>>>
... ("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):
... ("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
>>>
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>
>>>
... _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>
>>>
... ("b", c_float),
... ("point_array", POINT * 4)]
>>>
- >>> print len(MyStruct().point_array)
+ >>> print(len(MyStruct().point_array))
4
>>>
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.
>>> 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
>>>
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)
>>>
``NULL`` pointers have a ``False`` boolean value::
>>> null_ptr = POINTER(c_int)()
- >>> print bool(null_ptr)
+ >>> print(bool(null_ptr))
False
>>>
>>> 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
>>> bar = Bar()
>>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
- >>> print bar.values[0]
+ >>> print(bar.values[0])
0
>>>
>>> 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
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
...
>>>
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)
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]
...
>>>
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
>>>
api::
>>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
- >>> print opt_flag
+ >>> print(opt_flag)
c_long(0)
>>>
hit the NULL entry::
>>> for item in table:
- ... print item.name, item.size
+ ... print(item.name, item.size)
... if item.name is None:
... break
...
>>> 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
>>>
``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):
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()
def pi():
"""Compute Pi to the current precision.
- >>> print pi()
+ >>> print(pi())
3.141592653589793238462643383
"""
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)
"""
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)
"""
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)
"""
>>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
... 'ore\ntree\nemu\n'.splitlines(1))
- >>> print ''.join(diff),
+ >>> print(''.join(diff), end="")
- one
? ^
+ ore
>>> 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
>>> 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)
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
: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]
>>> x
12
>>> if x == 13:
- ... print "yes"
+ ... print("yes")
... else:
- ... print "no"
- ... print "NO"
- ... print "NO!!!"
+ ... print("no")
+ ... print("NO")
+ ... print("NO!!!")
...
no
NO
>>> 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,
>>> 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::
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]
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]
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]
>>> 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
>>> def f(x):
... g(x*2)
>>> def g(x):
- ... print x+3
+ ... print(x+3)
... import pdb; pdb.set_trace()
>>> f(3)
9
-> 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--
1 def f(x):
2 -> g(x*2)
[EOF]
- (Pdb) print x
+ (Pdb) p x
3
(Pdb) step
--Return--
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::
x, y = 1, 2
#
# Print their sum:
- print x+y
+ print(x+y)
# Expected:
## 3
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.
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``
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
>>> 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?=
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.
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)
structure::
>>> for part in msg.walk():
- ... print part.get_content_type()
+ ... print(part.get_content_type())
multipart/report
text/plain
message/delivery-status
for file in os.listdir('.'):
if fnmatch.fnmatch(file, '*.txt'):
- print file
+ print(file)
.. function:: fnmatchcase(filename, pattern)
>>> regex
'.*\\.txt$'
>>> reobj = re.compile(regex)
- >>> print reobj.match('foobar.txt')
+ >>> print(reobj.match('foobar.txt'))
<_sre.SRE_Match object at 0x...>
``(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
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
>>> 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
k = db.firstkey()
while k != None:
- print k
+ print(k)
k = db.nextkey(k)
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
gettext.textdomain('myapplication')
_ = gettext.gettext
# ...
- print _('This is a translatable string.')
+ print(_('This is a translatable string.'))
Class-based API
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
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.
]
# ...
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
# ...
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
# ...
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
>>> 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
>>>
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)
>>> 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()
>>> 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()
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()
>>> 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
>>> import operator
>>> for cube in imap(operator.pow, range(1,5), repeat(3)):
- ... print cube
+ ... print(cube)
...
1
8
>>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura',
... '', 'martin', '', 'walter', '', 'mark']
>>> for name in islice(reportlines, 3, None, 2):
- ... print name.title()
+ ... print(name.title())
...
Alex
Laura
>>> 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']
# 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]
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__":
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.
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::
>>> 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?
``"-n 42"`` (two arguments), the code ::
(options, args) = parser.parse_args(["-n42"])
- print options.num
+ print(options.num)
will print ``"42"``.
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__":
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
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)
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
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.
.. 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[:]
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
# 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()
return `obj`
aRepr = MyRepr()
- print aRepr.repr(sys.stdin) # prints '<stdin>'
+ print(aRepr.repr(sys.stdin)) # prints '<stdin>'
try:
import readline
except ImportError:
- print "Module readline not available."
+ print("Module readline not available.")
else:
import rlcompleter
readline.parse_and_bind("tab: complete")
>>> 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
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
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
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"
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)
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
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
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
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))
>>> 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)
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
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
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
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
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
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
"""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
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:
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:
... 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',)
(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
x = [0, 1]
i = 0
i, x[i] = 1, 2
- print x
+ print(x)
.. _augassign:
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.
... 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')
>>> 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!'
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
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
>>> 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
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`
>>> 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!
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::
# -*- 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
... 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
>>> 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
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