mirror of
https://github.com/python/cpython.git
synced 2025-07-24 11:44:31 +00:00
Tutorial update for 3.0 by Paul Dubois.
I had to fix a few markup issues in controlflow.rst and modules.rst. There's a unicode issue on line 448 in introduction.rst that someone else needs to fix.
This commit is contained in:
parent
8b2af27dae
commit
0616b792ba
12 changed files with 379 additions and 353 deletions
|
@ -14,7 +14,8 @@ multiple base classes, a derived class can override any methods of its base
|
|||
class or classes, and a method can call the method of a base class with the same
|
||||
name. Objects can contain an arbitrary amount of private data.
|
||||
|
||||
In C++ terminology, all class members (including the data members) are *public*,
|
||||
In C++ terminology, normally class members (including the data members) are
|
||||
*public* (except see below :ref:`tut-private`),
|
||||
and all member functions are *virtual*. There are no special constructors or
|
||||
destructors. As in Modula-3, there are no shorthands for referencing the
|
||||
object's members from its methods: the method function is declared with an
|
||||
|
@ -273,7 +274,7 @@ code will print the value ``16``, without leaving a trace::
|
|||
x.counter = 1
|
||||
while x.counter < 10:
|
||||
x.counter = x.counter * 2
|
||||
print x.counter
|
||||
print(x.counter)
|
||||
del x.counter
|
||||
|
||||
The other kind of instance attribute reference is a *method*. A method is a
|
||||
|
@ -308,7 +309,7 @@ object, and can be stored away and called at a later time. For example::
|
|||
|
||||
xf = x.f
|
||||
while True:
|
||||
print xf()
|
||||
print(xf())
|
||||
|
||||
will continue to print ``hello world`` until the end of time.
|
||||
|
||||
|
@ -621,11 +622,11 @@ following code will print B, C, D in that order::
|
|||
try:
|
||||
raise c()
|
||||
except D:
|
||||
print "D"
|
||||
print("D")
|
||||
except C:
|
||||
print "C"
|
||||
print("C")
|
||||
except B:
|
||||
print "B"
|
||||
print("B")
|
||||
|
||||
Note that if the except clauses were reversed (with ``except B`` first), it
|
||||
would have printed B, B, B --- the first matching except clause is triggered.
|
||||
|
@ -644,15 +645,15 @@ By now you have probably noticed that most container objects can be looped over
|
|||
using a :keyword:`for` statement::
|
||||
|
||||
for element in [1, 2, 3]:
|
||||
print element
|
||||
print(element)
|
||||
for element in (1, 2, 3):
|
||||
print element
|
||||
print(element)
|
||||
for key in {'one':1, 'two':2}:
|
||||
print key
|
||||
print(key)
|
||||
for char in "123":
|
||||
print char
|
||||
print(char)
|
||||
for line in open("myfile.txt"):
|
||||
print line
|
||||
print(line)
|
||||
|
||||
This style of access is clear, concise, and convenient. The use of iterators
|
||||
pervades and unifies Python. Behind the scenes, the :keyword:`for` statement
|
||||
|
@ -699,7 +700,7 @@ returns an object with a :meth:`__next__` method. If the class defines
|
|||
return self.data[self.index]
|
||||
|
||||
>>> for char in Reverse('spam'):
|
||||
... print char
|
||||
... print(char)
|
||||
...
|
||||
m
|
||||
a
|
||||
|
@ -724,7 +725,7 @@ create::
|
|||
yield data[index]
|
||||
|
||||
>>> for char in reverse('golf'):
|
||||
... print char
|
||||
... print(char)
|
||||
...
|
||||
f
|
||||
l
|
||||
|
|
|
@ -19,13 +19,13 @@ example::
|
|||
>>> x = int(input("Please enter an integer: "))
|
||||
>>> if x < 0:
|
||||
... x = 0
|
||||
... print 'Negative changed to zero'
|
||||
... print('Negative changed to zero')
|
||||
... elif x == 0:
|
||||
... print 'Zero'
|
||||
... print('Zero')
|
||||
... elif x == 1:
|
||||
... print 'Single'
|
||||
... print('Single')
|
||||
... else:
|
||||
... print 'More'
|
||||
... print('More')
|
||||
...
|
||||
|
||||
There can be zero or more :keyword:`elif` parts, and the :keyword:`else` part is
|
||||
|
@ -45,7 +45,6 @@ to avoid excessive indentation. An :keyword:`if` ... :keyword:`elif` ...
|
|||
|
||||
.. index::
|
||||
statement: for
|
||||
statement: for
|
||||
|
||||
The :keyword:`for` statement in Python differs a bit from what you may be used
|
||||
to in C or Pascal. Rather than always iterating over an arithmetic progression
|
||||
|
@ -62,7 +61,7 @@ they appear in the sequence. For example (no pun intended):
|
|||
>>> # Measure some strings:
|
||||
... a = ['cat', 'window', 'defenestrate']
|
||||
>>> for x in a:
|
||||
... print x, len(x)
|
||||
... print(x, len(x))
|
||||
...
|
||||
cat 3
|
||||
window 6
|
||||
|
@ -87,30 +86,40 @@ The :func:`range` Function
|
|||
==========================
|
||||
|
||||
If you do need to iterate over a sequence of numbers, the built-in function
|
||||
:func:`range` comes in handy. It generates lists containing arithmetic
|
||||
progressions::
|
||||
:func:`range` comes in handy. It generates arithmetic progressions::
|
||||
|
||||
|
||||
>>> for i in range(5):
|
||||
... print(i)
|
||||
...
|
||||
0
|
||||
1
|
||||
2
|
||||
3
|
||||
4
|
||||
|
||||
|
||||
>>> range(10)
|
||||
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||
|
||||
The given end point is never part of the generated list; ``range(10)`` generates
|
||||
a list of 10 values, the legal indices for items of a sequence of length 10. It
|
||||
10 values, the legal indices for items of a sequence of length 10. It
|
||||
is possible to let the range start at another number, or to specify a different
|
||||
increment (even negative; sometimes this is called the 'step')::
|
||||
|
||||
>>> range(5, 10)
|
||||
[5, 6, 7, 8, 9]
|
||||
>>> range(0, 10, 3)
|
||||
[0, 3, 6, 9]
|
||||
>>> range(-10, -100, -30)
|
||||
[-10, -40, -70]
|
||||
range(5, 10)
|
||||
5 through 9
|
||||
|
||||
range(0, 10, 3)
|
||||
0, 3, 6, 9
|
||||
|
||||
range(-10, -100, -30)
|
||||
-10, -40, -70
|
||||
|
||||
To iterate over the indices of a sequence, combine :func:`range` and :func:`len`
|
||||
as follows::
|
||||
|
||||
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
|
||||
>>> for i in range(len(a)):
|
||||
... print i, a[i]
|
||||
... print(i, a[i])
|
||||
...
|
||||
0 Mary
|
||||
1 had
|
||||
|
@ -118,6 +127,27 @@ as follows::
|
|||
3 little
|
||||
4 lamb
|
||||
|
||||
A strange thing happens if you just print a range::
|
||||
|
||||
>>> print(range(10))
|
||||
range(0, 10)
|
||||
|
||||
In many ways the object returned by :func:`range` behaves as if it is a list,
|
||||
but in fact it isn't. It is an object which returns the successive items of
|
||||
the desired sequence when you iterate over it, but it doesn't really make
|
||||
the list, thus saving space.
|
||||
|
||||
We say such an object is *iterable*, that is, suitable as a target for
|
||||
functions and constructs that expect something from which they can
|
||||
obtain successive items until the supply is exhausted. We have seen that
|
||||
the :keyword:`for` statement is such an *iterator*. The function :func:`list`
|
||||
is another; it creates lists from iterables::
|
||||
|
||||
|
||||
>>> list(range(5))
|
||||
[0, 1, 2, 3, 4]
|
||||
|
||||
Later we will see more functions that return iterables and take iterables as argument.
|
||||
|
||||
.. _tut-break:
|
||||
|
||||
|
@ -139,11 +169,11 @@ following loop, which searches for prime numbers::
|
|||
>>> for n in range(2, 10):
|
||||
... for x in range(2, n):
|
||||
... if n % x == 0:
|
||||
... print n, 'equals', x, '*', n/x
|
||||
... print(n, 'equals', x, '*', n/x)
|
||||
... break
|
||||
... else:
|
||||
... # loop fell through without finding a factor
|
||||
... print n, 'is a prime number'
|
||||
... print(n, 'is a prime number')
|
||||
...
|
||||
2 is a prime number
|
||||
3 is a prime number
|
||||
|
@ -180,8 +210,9 @@ boundary::
|
|||
... """Print a Fibonacci series up to n."""
|
||||
... a, b = 0, 1
|
||||
... while b < n:
|
||||
... print b,
|
||||
... print(b,end=' ')
|
||||
... a, b = b, a+b
|
||||
... print()
|
||||
...
|
||||
>>> # Now call the function we just defined:
|
||||
... fib(2000)
|
||||
|
@ -237,7 +268,7 @@ This value is called ``None`` (it's a built-in name). Writing the value
|
|||
``None`` is normally suppressed by the interpreter if it would be the only value
|
||||
written. You can see it if you really want to::
|
||||
|
||||
>>> print fib(0)
|
||||
>>> print(fib(0))
|
||||
None
|
||||
|
||||
It is simple to write a function that returns a list of the numbers of the
|
||||
|
@ -299,7 +330,7 @@ defined to allow. For example::
|
|||
if ok in ('n', 'no', 'nop', 'nope'): return False
|
||||
retries = retries - 1
|
||||
if retries < 0: raise IOError, 'refusenik user'
|
||||
print complaint
|
||||
print(complaint)
|
||||
|
||||
This function can be called either like this: ``ask_ok('Do you really want to
|
||||
quit?')`` or like this: ``ask_ok('OK to overwrite the file?', 2)``.
|
||||
|
@ -313,7 +344,7 @@ The default values are evaluated at the point of function definition in the
|
|||
i = 5
|
||||
|
||||
def f(arg=i):
|
||||
print arg
|
||||
print(arg)
|
||||
|
||||
i = 6
|
||||
f()
|
||||
|
@ -329,9 +360,9 @@ arguments passed to it on subsequent calls::
|
|||
L.append(a)
|
||||
return L
|
||||
|
||||
print f(1)
|
||||
print f(2)
|
||||
print f(3)
|
||||
print(f(1))
|
||||
print(f(2))
|
||||
print(f(3))
|
||||
|
||||
This will print ::
|
||||
|
||||
|
@ -358,10 +389,10 @@ Functions can also be called using keyword arguments of the form ``keyword =
|
|||
value``. For instance, the following function::
|
||||
|
||||
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
|
||||
print "-- This parrot wouldn't", action,
|
||||
print "if you put", voltage, "volts through it."
|
||||
print "-- Lovely plumage, the", type
|
||||
print "-- It's", state, "!"
|
||||
print("-- This parrot wouldn't", action, end= ' ')
|
||||
print("if you put", voltage, "volts through it.")
|
||||
print("-- Lovely plumage, the", type)
|
||||
print("-- It's", state, "!")
|
||||
|
||||
could be called in any of the following ways::
|
||||
|
||||
|
@ -401,13 +432,13 @@ list. (``*name`` must occur before ``**name``.) For example, if we define a
|
|||
function like this::
|
||||
|
||||
def cheeseshop(kind, *arguments, **keywords):
|
||||
print "-- Do you have any", kind, '?'
|
||||
print "-- I'm sorry, we're all out of", kind
|
||||
print("-- Do you have any", kind, '?')
|
||||
print("-- I'm sorry, we're all out of", kind)
|
||||
for arg in arguments: print arg
|
||||
print '-'*40
|
||||
print('-'*40)
|
||||
keys = keywords.keys()
|
||||
keys.sort()
|
||||
for kw in keys: print kw, ':', keywords[kw]
|
||||
for kw in keys: print(kw, ':', keywords[kw])
|
||||
|
||||
It could be called like this::
|
||||
|
||||
|
@ -446,6 +477,20 @@ arguments may occur. ::
|
|||
def fprintf(file, format, *args):
|
||||
file.write(format % args)
|
||||
|
||||
|
||||
Normally, these ``variadic`` arguments will be last in the list of formal
|
||||
parameters, because they scoop up all remaining input arguments that are
|
||||
passed to the function. Any formal parameters which occur after the ``*args``
|
||||
parameter are 'keyword-only' arguments, meaning that they can only be used as
|
||||
keywords rather than positional arguments.::
|
||||
|
||||
>>> def concat(*args, sep="/"):
|
||||
... return sep.join(args)
|
||||
...
|
||||
>>> concat("earth", "mars", "venus")
|
||||
'earth/mars/venus'
|
||||
>>> concat("earth", "mars", "venus", sep=".")
|
||||
'earth.mars.venus'
|
||||
|
||||
.. _tut-unpacking-arguments:
|
||||
|
||||
|
@ -459,19 +504,19 @@ arguments. For instance, the built-in :func:`range` function expects separate
|
|||
function call with the ``*``\ -operator to unpack the arguments out of a list
|
||||
or tuple::
|
||||
|
||||
>>> range(3, 6) # normal call with separate arguments
|
||||
>>> list(range(3, 6)) # normal call with separate arguments
|
||||
[3, 4, 5]
|
||||
>>> args = [3, 6]
|
||||
>>> range(*args) # call with arguments unpacked from a list
|
||||
>>> list(range(*args)) # call with arguments unpacked from a list
|
||||
[3, 4, 5]
|
||||
|
||||
In the same fashion, dictionaries can deliver keyword arguments with the ``**``\
|
||||
-operator::
|
||||
|
||||
>>> def parrot(voltage, state='a stiff', action='voom'):
|
||||
... print "-- This parrot wouldn't", action,
|
||||
... print "if you put", voltage, "volts through it.",
|
||||
... print "E's", state, "!"
|
||||
... print("-- This parrot wouldn't", action,end=' ')
|
||||
... print("if you put", voltage, "volts through it.", end=' ')
|
||||
... print("E's", state, "!")
|
||||
...
|
||||
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
|
||||
>>> parrot(**d)
|
||||
|
@ -512,8 +557,8 @@ Documentation Strings
|
|||
single: documentation strings
|
||||
single: strings, documentation
|
||||
|
||||
There are emerging conventions about the content and formatting of documentation
|
||||
strings.
|
||||
Here are some conventions about the content and formatting of documentation
|
||||
strings.
|
||||
|
||||
The first line should always be a short, concise summary of the object's
|
||||
purpose. For brevity, it should not explicitly state the object's name or type,
|
||||
|
@ -547,7 +592,7 @@ Here is an example of a multi-line docstring::
|
|||
... """
|
||||
... pass
|
||||
...
|
||||
>>> print my_function.__doc__
|
||||
>>> print(my_function.__doc__)
|
||||
Do nothing, but document it.
|
||||
|
||||
No, really, it doesn't do anything.
|
||||
|
|
|
@ -7,6 +7,71 @@ Data Structures
|
|||
This chapter describes some things you've learned about already in more detail,
|
||||
and adds some new things as well.
|
||||
|
||||
.. _tut-tuples:
|
||||
|
||||
Tuples and Sequences
|
||||
====================
|
||||
|
||||
We saw that lists and strings have many common properties, such as indexing and
|
||||
slicing operations. They are two examples of *sequence* data types (see
|
||||
:ref:`typesseq`). Since Python is an evolving language, other sequence data
|
||||
types may be added. There is also another standard sequence data type: the
|
||||
*tuple*.
|
||||
|
||||
A tuple consists of a number of values separated by commas, for instance::
|
||||
|
||||
>>> t = 12345, 54321, 'hello!'
|
||||
>>> t[0]
|
||||
12345
|
||||
>>> t
|
||||
(12345, 54321, 'hello!')
|
||||
>>> # Tuples may be nested:
|
||||
... u = t, (1, 2, 3, 4, 5)
|
||||
>>> u
|
||||
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
|
||||
|
||||
As you see, on output tuples are always enclosed in parentheses, so that nested
|
||||
tuples are interpreted correctly; they may be input with or without surrounding
|
||||
parentheses, although often parentheses are necessary anyway (if the tuple is
|
||||
part of a larger expression).
|
||||
|
||||
Tuples have many uses. For example: (x, y) coordinate pairs, employee records
|
||||
from a database, etc. Tuples, like strings, are immutable: it is not possible
|
||||
to assign to the individual items of a tuple (you can simulate much of the same
|
||||
effect with slicing and concatenation, though). It is also possible to create
|
||||
tuples which contain mutable objects, such as lists.
|
||||
|
||||
A special problem is the construction of tuples containing 0 or 1 items: the
|
||||
syntax has some extra quirks to accommodate these. Empty tuples are constructed
|
||||
by an empty pair of parentheses; a tuple with one item is constructed by
|
||||
following a value with a comma (it is not sufficient to enclose a single value
|
||||
in parentheses). Ugly, but effective. For example::
|
||||
|
||||
>>> empty = ()
|
||||
>>> singleton = 'hello', # <-- note trailing comma
|
||||
>>> len(empty)
|
||||
0
|
||||
>>> len(singleton)
|
||||
1
|
||||
>>> singleton
|
||||
('hello',)
|
||||
|
||||
The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
|
||||
the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
|
||||
The reverse operation is also possible::
|
||||
|
||||
>>> x, y, z = t
|
||||
|
||||
This is called, appropriately enough, *sequence unpacking*. Sequence unpacking
|
||||
requires the list of variables on the left to have the same number of elements
|
||||
as the length of the sequence. Note that multiple assignment is really just a
|
||||
combination of tuple packing and sequence unpacking!
|
||||
|
||||
There is a small bit of asymmetry here: packing multiple values always creates
|
||||
a tuple, and unpacking works for any sequence.
|
||||
|
||||
.. % XXX Add a bit on the difference between tuples and lists.
|
||||
|
||||
|
||||
.. _tut-morelists:
|
||||
|
||||
|
@ -73,7 +138,7 @@ objects:
|
|||
An example that uses most of the list methods::
|
||||
|
||||
>>> a = [66.25, 333, 333, 1, 1234.5]
|
||||
>>> print a.count(333), a.count(66.25), a.count('x')
|
||||
>>> print(a.count(333), a.count(66.25), a.count('x'))
|
||||
2 1 0
|
||||
>>> a.insert(2, -1)
|
||||
>>> a.append(333)
|
||||
|
@ -146,71 +211,47 @@ the queue, use :meth:`pop` with ``0`` as the index. For example::
|
|||
['Michael', 'Terry', 'Graham']
|
||||
|
||||
|
||||
.. _tut-functional:
|
||||
|
||||
Functional Programming Tools
|
||||
----------------------------
|
||||
|
||||
There are two built-in functions that are very useful when used with lists:
|
||||
:func:`filter` and :func:`map`.
|
||||
|
||||
``filter(function, sequence)`` returns a sequence consisting of those items from
|
||||
the sequence for which ``function(item)`` is true. If *sequence* is a
|
||||
:class:`string` or :class:`tuple`, the result will be of the same type;
|
||||
otherwise, it is always a :class:`list`. For example, to compute some primes::
|
||||
|
||||
>>> def f(x): return x % 2 != 0 and x % 3 != 0
|
||||
...
|
||||
>>> filter(f, range(2, 25))
|
||||
[5, 7, 11, 13, 17, 19, 23]
|
||||
|
||||
``map(function, sequence)`` calls ``function(item)`` for each of the sequence's
|
||||
items and returns a list of the return values. For example, to compute some
|
||||
cubes::
|
||||
|
||||
>>> def cube(x): return x*x*x
|
||||
...
|
||||
>>> map(cube, range(1, 11))
|
||||
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
|
||||
|
||||
More than one sequence may be passed; the function must then have as many
|
||||
arguments as there are sequences and is called with the corresponding item from
|
||||
each sequence (or ``None`` if some sequence is shorter than another). For
|
||||
example::
|
||||
|
||||
>>> seq = range(8)
|
||||
>>> def add(x, y): return x+y
|
||||
...
|
||||
>>> map(add, seq, seq)
|
||||
[0, 2, 4, 6, 8, 10, 12, 14]
|
||||
|
||||
.. versionadded:: 2.3
|
||||
|
||||
|
||||
List Comprehensions
|
||||
-------------------
|
||||
|
||||
List comprehensions provide a concise way to create lists without resorting to
|
||||
use of :func:`map`, :func:`filter` and/or :keyword:`lambda`. The resulting list
|
||||
definition tends often to be clearer than lists built using those constructs.
|
||||
List comprehensions provide a concise way to create lists from sequences.
|
||||
Common applications are to make lists where each element is the result of
|
||||
some operations applied to each member of the sequence, or to create a
|
||||
subsequence of those elements that satisfy a certain condition.
|
||||
|
||||
|
||||
Each list comprehension consists of an expression followed by a :keyword:`for`
|
||||
clause, then zero or more :keyword:`for` or :keyword:`if` clauses. The result
|
||||
will be a list resulting from evaluating the expression in the context of the
|
||||
:keyword:`for` and :keyword:`if` clauses which follow it. If the expression
|
||||
would evaluate to a tuple, it must be parenthesized. ::
|
||||
would evaluate to a tuple, it must be parenthesized.
|
||||
|
||||
Here we take a list of numbers and return a list of three times each number::
|
||||
|
||||
>>> vec = [2, 4, 6]
|
||||
>>> [3*x for x in vec]
|
||||
[6, 12, 18]
|
||||
|
||||
Now we get a little fancier::
|
||||
|
||||
>>> [[x,x**2] for x in vec]
|
||||
[[2, 4], [4, 16], [6, 36]]
|
||||
|
||||
Here we apply a method call to each item in a sequence::
|
||||
|
||||
>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
|
||||
>>> [weapon.strip() for weapon in freshfruit]
|
||||
['banana', 'loganberry', 'passion fruit']
|
||||
>>> vec = [2, 4, 6]
|
||||
>>> [3*x for x in vec]
|
||||
[6, 12, 18]
|
||||
|
||||
Using the if-clause we can filter the stream::
|
||||
|
||||
>>> [3*x for x in vec if x > 3]
|
||||
[12, 18]
|
||||
>>> [3*x for x in vec if x < 2]
|
||||
[]
|
||||
>>> [[x,x**2] for x in vec]
|
||||
[[2, 4], [4, 16], [6, 36]]
|
||||
|
||||
Tuples can often be created without their parentheses, but not here::
|
||||
|
||||
>>> [x, x**2 for x in vec] # error - parens required for tuples
|
||||
File "<stdin>", line 1, in ?
|
||||
[x, x**2 for x in vec]
|
||||
|
@ -218,6 +259,9 @@ would evaluate to a tuple, it must be parenthesized. ::
|
|||
SyntaxError: invalid syntax
|
||||
>>> [(x, x**2) for x in vec]
|
||||
[(2, 4), (4, 16), (6, 36)]
|
||||
|
||||
Here are some nested for's and other fancy behavior::
|
||||
|
||||
>>> vec1 = [2, 4, 6]
|
||||
>>> vec2 = [4, 3, -9]
|
||||
>>> [x*y for x in vec1 for y in vec2]
|
||||
|
@ -227,8 +271,7 @@ would evaluate to a tuple, it must be parenthesized. ::
|
|||
>>> [vec1[i]*vec2[i] for i in range(len(vec1))]
|
||||
[8, 12, -54]
|
||||
|
||||
List comprehensions are much more flexible than :func:`map` and can be applied
|
||||
to complex expressions and nested functions::
|
||||
List comprehensions can be applied to complex expressions and nested functions::
|
||||
|
||||
>>> [str(round(355/113.0, i)) for i in range(1,6)]
|
||||
['3.1', '3.14', '3.142', '3.1416', '3.14159']
|
||||
|
@ -264,71 +307,6 @@ Referencing the name ``a`` hereafter is an error (at least until another value
|
|||
is assigned to it). We'll find other uses for :keyword:`del` later.
|
||||
|
||||
|
||||
.. _tut-tuples:
|
||||
|
||||
Tuples and Sequences
|
||||
====================
|
||||
|
||||
We saw that lists and strings have many common properties, such as indexing and
|
||||
slicing operations. They are two examples of *sequence* data types (see
|
||||
:ref:`typesseq`). Since Python is an evolving language, other sequence data
|
||||
types may be added. There is also another standard sequence data type: the
|
||||
*tuple*.
|
||||
|
||||
A tuple consists of a number of values separated by commas, for instance::
|
||||
|
||||
>>> t = 12345, 54321, 'hello!'
|
||||
>>> t[0]
|
||||
12345
|
||||
>>> t
|
||||
(12345, 54321, 'hello!')
|
||||
>>> # Tuples may be nested:
|
||||
... u = t, (1, 2, 3, 4, 5)
|
||||
>>> u
|
||||
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
|
||||
|
||||
As you see, on output tuples are always enclosed in parentheses, so that nested
|
||||
tuples are interpreted correctly; they may be input with or without surrounding
|
||||
parentheses, although often parentheses are necessary anyway (if the tuple is
|
||||
part of a larger expression).
|
||||
|
||||
Tuples have many uses. For example: (x, y) coordinate pairs, employee records
|
||||
from a database, etc. Tuples, like strings, are immutable: it is not possible
|
||||
to assign to the individual items of a tuple (you can simulate much of the same
|
||||
effect with slicing and concatenation, though). It is also possible to create
|
||||
tuples which contain mutable objects, such as lists.
|
||||
|
||||
A special problem is the construction of tuples containing 0 or 1 items: the
|
||||
syntax has some extra quirks to accommodate these. Empty tuples are constructed
|
||||
by an empty pair of parentheses; a tuple with one item is constructed by
|
||||
following a value with a comma (it is not sufficient to enclose a single value
|
||||
in parentheses). Ugly, but effective. For example::
|
||||
|
||||
>>> empty = ()
|
||||
>>> singleton = 'hello', # <-- note trailing comma
|
||||
>>> len(empty)
|
||||
0
|
||||
>>> len(singleton)
|
||||
1
|
||||
>>> singleton
|
||||
('hello',)
|
||||
|
||||
The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
|
||||
the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
|
||||
The reverse operation is also possible::
|
||||
|
||||
>>> x, y, z = t
|
||||
|
||||
This is called, appropriately enough, *sequence unpacking*. Sequence unpacking
|
||||
requires the list of variables on the left to have the same number of elements
|
||||
as the length of the sequence. Note that multiple assignment is really just a
|
||||
combination of tuple packing and sequence unpacking!
|
||||
|
||||
There is a small bit of asymmetry here: packing multiple values always creates
|
||||
a tuple, and unpacking works for any sequence.
|
||||
|
||||
.. % XXX Add a bit on the difference between tuples and lists.
|
||||
|
||||
|
||||
.. _tut-sets:
|
||||
|
||||
|
@ -340,12 +318,19 @@ with no duplicate elements. Basic uses include membership testing and
|
|||
eliminating duplicate entries. Set objects also support mathematical operations
|
||||
like union, intersection, difference, and symmetric difference.
|
||||
|
||||
Curly braces or the :func:`set` function can be use to create sets. Note:
|
||||
To create an empty set you have to use set(), not {}; the latter creates
|
||||
an empty dictionary, a data structure that we discuss in the next section.
|
||||
|
||||
Here is a brief demonstration::
|
||||
|
||||
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
|
||||
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
|
||||
>>> print(basket)
|
||||
{'orange', 'bananna', 'pear', 'apple'}
|
||||
>>> fruit = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
|
||||
>>> fruit = set(basket) # create a set without duplicates
|
||||
>>> fruit
|
||||
set(['orange', 'pear', 'apple', 'banana'])
|
||||
{'orange', 'pear', 'apple', 'banana'}
|
||||
>>> 'orange' in fruit # fast membership testing
|
||||
True
|
||||
>>> 'crabgrass' in fruit
|
||||
|
@ -356,15 +341,17 @@ Here is a brief demonstration::
|
|||
>>> a = set('abracadabra')
|
||||
>>> b = set('alacazam')
|
||||
>>> a # unique letters in a
|
||||
set(['a', 'r', 'b', 'c', 'd'])
|
||||
{'a', 'r', 'b', 'c', 'd'}
|
||||
>>> a - b # letters in a but not in b
|
||||
set(['r', 'd', 'b'])
|
||||
{'r', 'd', 'b'}
|
||||
>>> a | b # letters in either a or b
|
||||
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
|
||||
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
|
||||
>>> a & b # letters in both a and b
|
||||
set(['a', 'c'])
|
||||
{'a', 'c'}
|
||||
>>> a ^ b # letters in a or b but not both
|
||||
set(['r', 'd', 'b', 'm', 'z', 'l'])
|
||||
{'r', 'd', 'b', 'm', 'z', 'l'}
|
||||
|
||||
|
||||
|
||||
|
||||
.. _tut-dictionaries:
|
||||
|
@ -441,6 +428,8 @@ keyword arguments::
|
|||
|
||||
|
||||
.. _tut-loopidioms:
|
||||
.. %
|
||||
Find out the right way to do these DUBOIS
|
||||
|
||||
Looping Techniques
|
||||
==================
|
||||
|
@ -450,7 +439,7 @@ retrieved at the same time using the :meth:`iteritems` method. ::
|
|||
|
||||
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
|
||||
>>> for k, v in knights.iteritems():
|
||||
... print k, v
|
||||
... print(k, v)
|
||||
...
|
||||
gallahad the pure
|
||||
robin the brave
|
||||
|
@ -459,7 +448,7 @@ When looping through a sequence, the position index and corresponding value can
|
|||
be retrieved at the same time using the :func:`enumerate` function. ::
|
||||
|
||||
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
|
||||
... print i, v
|
||||
... print(i, v)
|
||||
...
|
||||
0 tic
|
||||
1 tac
|
||||
|
@ -471,7 +460,7 @@ with the :func:`zip` function. ::
|
|||
>>> questions = ['name', 'quest', 'favorite color']
|
||||
>>> answers = ['lancelot', 'the holy grail', 'blue']
|
||||
>>> for q, a in zip(questions, answers):
|
||||
... print 'What is your %s? It is %s.' % (q, a)
|
||||
... print('What is your %s? It is %s.' % (q, a))
|
||||
...
|
||||
What is your name? It is lancelot.
|
||||
What is your quest? It is the holy grail.
|
||||
|
@ -481,7 +470,7 @@ To loop over a sequence in reverse, first specify the sequence in a forward
|
|||
direction and then call the :func:`reversed` function. ::
|
||||
|
||||
>>> for i in reversed(range(1,10,2)):
|
||||
... print i
|
||||
... print(i)
|
||||
...
|
||||
9
|
||||
7
|
||||
|
@ -494,7 +483,7 @@ returns a new sorted list while leaving the source unaltered. ::
|
|||
|
||||
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
|
||||
>>> for f in sorted(set(basket)):
|
||||
... print f
|
||||
... print(f)
|
||||
...
|
||||
apple
|
||||
banana
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
.. _tut-errors:
|
||||
. _tut-errors:
|
||||
|
||||
*********************
|
||||
Errors and Exceptions
|
||||
|
@ -17,9 +17,9 @@ Syntax Errors
|
|||
Syntax errors, also known as parsing errors, are perhaps the most common kind of
|
||||
complaint you get while you are still learning Python::
|
||||
|
||||
>>> while True print 'Hello world'
|
||||
>>> while True print('Hello world')
|
||||
File "<stdin>", line 1, in ?
|
||||
while True print 'Hello world'
|
||||
while True print('Hello world')
|
||||
^
|
||||
SyntaxError: invalid syntax
|
||||
|
||||
|
@ -45,7 +45,7 @@ programs, however, and result in error messages as shown here::
|
|||
>>> 10 * (1/0)
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in ?
|
||||
ZeroDivisionError: integer division or modulo by zero
|
||||
ZeroDivisionError: int division or modulo by zero
|
||||
>>> 4 + spam*3
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in ?
|
||||
|
@ -53,7 +53,7 @@ programs, however, and result in error messages as shown here::
|
|||
>>> '2' + 2
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in ?
|
||||
TypeError: cannot concatenate 'str' and 'int' objects
|
||||
TypeError: coercing to Unicode: need string or buffer, int found
|
||||
|
||||
The last line of the error message indicates what happened. Exceptions come in
|
||||
different types, and the type is printed as part of the message: the types in
|
||||
|
@ -90,7 +90,7 @@ is signalled by raising the :exc:`KeyboardInterrupt` exception. ::
|
|||
... x = int(input("Please enter a number: "))
|
||||
... break
|
||||
... except ValueError:
|
||||
... print "Oops! That was no valid number. Try again..."
|
||||
... print("Oops! That was no valid number. Try again...")
|
||||
...
|
||||
|
||||
The :keyword:`try` statement works as follows.
|
||||
|
@ -132,12 +132,11 @@ the exception (allowing a caller to handle the exception as well)::
|
|||
s = f.readline()
|
||||
i = int(s.strip())
|
||||
except IOError as e:
|
||||
(errno, strerror) = e
|
||||
print "I/O error(%s): %s" % (e.errno, e.strerror)
|
||||
print("I/O error(%s): %s" % (e.errno, e.strerror))
|
||||
except ValueError:
|
||||
print "Could not convert data to an integer."
|
||||
print("Could not convert data to an integer.")
|
||||
except:
|
||||
print "Unexpected error:", sys.exc_info()[0]
|
||||
print("Unexpected error:", sys.exc_info()[0])
|
||||
raise
|
||||
|
||||
The :keyword:`try` ... :keyword:`except` statement has an optional *else
|
||||
|
@ -149,9 +148,9 @@ example::
|
|||
try:
|
||||
f = open(arg, 'r')
|
||||
except IOError:
|
||||
print 'cannot open', arg
|
||||
print('cannot open', arg)
|
||||
else:
|
||||
print arg, 'has', len(f.readlines()), 'lines'
|
||||
print(arg, 'has', len(f.readlines()), 'lines')
|
||||
f.close()
|
||||
|
||||
The use of the :keyword:`else` clause is better than adding additional code to
|
||||
|
@ -178,9 +177,9 @@ desired. ::
|
|||
>>> try:
|
||||
... raise Exception('spam', 'eggs')
|
||||
... except Exception as inst:
|
||||
... print type(inst) # the exception instance
|
||||
... print inst.args # arguments stored in .args
|
||||
... print inst # __str__ allows args to printed directly
|
||||
... print(type(inst)) # the exception instance
|
||||
... 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
|
||||
|
@ -204,7 +203,7 @@ indirectly) in the try clause. For example::
|
|||
>>> try:
|
||||
... this_fails()
|
||||
... except ZeroDivisionError as detail:
|
||||
... print 'Handling run-time error:', detail
|
||||
... print('Handling run-time error:', detail)
|
||||
...
|
||||
Handling run-time error: integer division or modulo by zero
|
||||
|
||||
|
@ -234,7 +233,7 @@ re-raise the exception::
|
|||
>>> try:
|
||||
... raise NameError, 'HiThere'
|
||||
... except NameError:
|
||||
... print 'An exception flew by!'
|
||||
... print('An exception flew by!')
|
||||
... raise
|
||||
...
|
||||
An exception flew by!
|
||||
|
@ -331,7 +330,7 @@ example::
|
|||
>>> try:
|
||||
... raise KeyboardInterrupt
|
||||
... finally:
|
||||
... print 'Goodbye, world!'
|
||||
... print('Goodbye, world!')
|
||||
...
|
||||
Goodbye, world!
|
||||
Traceback (most recent call last):
|
||||
|
@ -353,11 +352,11 @@ the same :keyword:`try` statement works as of Python 2.5)::
|
|||
... try:
|
||||
... result = x / y
|
||||
... except ZeroDivisionError:
|
||||
... print "division by zero!"
|
||||
... print("division by zero!")
|
||||
... else:
|
||||
... print "result is", result
|
||||
... print("result is", result)
|
||||
... finally:
|
||||
... print "executing finally clause"
|
||||
... print("executing finally clause")
|
||||
...
|
||||
>>> divide(2, 1)
|
||||
result is 2
|
||||
|
@ -393,20 +392,20 @@ succeeded or failed. Look at the following example, which tries to open a file
|
|||
and print its contents to the screen. ::
|
||||
|
||||
for line in open("myfile.txt"):
|
||||
print line
|
||||
print(line)
|
||||
|
||||
The problem with this code is that it leaves the file open for an indeterminate
|
||||
amount of time after the code has finished executing. This is not an issue in
|
||||
simple scripts, but can be a problem for larger applications. The
|
||||
:keyword:`with` statement allows objects like files to be used in a way that
|
||||
ensures they are always cleaned up promptly and correctly. ::
|
||||
amount of time after this part of the code has finished executing.
|
||||
This is not an issue in simple scripts, but can be a problem for larger
|
||||
applications. The :keyword:`with` statement allows objects like files to be
|
||||
used in a way that ensures they are always cleaned up promptly and correctly. ::
|
||||
|
||||
with open("myfile.txt") as f:
|
||||
for line in f:
|
||||
print line
|
||||
print(line)
|
||||
|
||||
After the statement is executed, the file *f* is always closed, even if a
|
||||
problem was encountered while processing the lines. Other objects which provide
|
||||
predefined clean-up actions will indicate this in their documentation.
|
||||
problem was encountered while processing the lines. Objects which, like files,
|
||||
provide predefined clean-up actions will indicate this in their documentation.
|
||||
|
||||
|
||||
|
|
|
@ -136,7 +136,10 @@ display of your final results to the number of decimal digits you expect.
|
|||
Python's ``%`` format operator: the ``%g``, ``%f`` and ``%e`` format codes
|
||||
supply flexible and easy ways to round float results for display.
|
||||
|
||||
|
||||
If you are a heavy user of floating point operations you should take a look
|
||||
at the Numerical Python package and many other packages for mathematical and
|
||||
statistical operations supplied by the SciPy project. See <http://scipy.org>.
|
||||
|
||||
.. _tut-fp-error:
|
||||
|
||||
Representation Error
|
||||
|
|
|
@ -15,7 +15,7 @@ Fancier Output Formatting
|
|||
=========================
|
||||
|
||||
So far we've encountered two ways of writing values: *expression statements* and
|
||||
the :keyword:`print` statement. (A third way is using the :meth:`write` method
|
||||
the :func:`print` function. (A third way is using the :meth:`write` method
|
||||
of file objects; the standard output file can be referenced as ``sys.stdout``.
|
||||
See the Library Reference for more information on this.)
|
||||
|
||||
|
@ -61,12 +61,12 @@ Some examples::
|
|||
>>> x = 10 * 3.25
|
||||
>>> y = 200 * 200
|
||||
>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
|
||||
>>> print s
|
||||
>>> print(s)
|
||||
The value of x is 32.5, and y is 40000...
|
||||
>>> # The repr() of a string adds string quotes and backslashes:
|
||||
... hello = 'hello, world\n'
|
||||
>>> hellos = repr(hello)
|
||||
>>> print hellos
|
||||
>>> print(hellos)
|
||||
'hello, world\n'
|
||||
>>> # The argument to repr() may be any Python object:
|
||||
... repr((x, y, ('spam', 'eggs')))
|
||||
|
@ -78,9 +78,9 @@ Some examples::
|
|||
Here are two ways to write a table of squares and cubes::
|
||||
|
||||
>>> for x in range(1, 11):
|
||||
... print repr(x).rjust(2), repr(x*x).rjust(3),
|
||||
... # Note trailing comma on previous line
|
||||
... print repr(x*x*x).rjust(4)
|
||||
... print(repr(x).rjust(2), repr(x*x).rjust(3),end=' ')
|
||||
... # Note use of 'end' on previous line
|
||||
... print(repr(x*x*x).rjust(4))
|
||||
...
|
||||
1 1 1
|
||||
2 4 8
|
||||
|
@ -94,7 +94,7 @@ Here are two ways to write a table of squares and cubes::
|
|||
10 100 1000
|
||||
|
||||
>>> for x in range(1,11):
|
||||
... print '%2d %3d %4d' % (x, x*x, x*x*x)
|
||||
... print('%2d %3d %4d' % (x, x*x, x*x*x))
|
||||
...
|
||||
1 1 1
|
||||
2 4 8
|
||||
|
@ -108,7 +108,7 @@ Here are two ways to write a table of squares and cubes::
|
|||
10 100 1000
|
||||
|
||||
(Note that in the first example, one space between each column was added by the
|
||||
way :keyword:`print` works: it always adds spaces between its arguments.)
|
||||
way :func:`print` works: it always adds spaces between its arguments.)
|
||||
|
||||
This example demonstrates the :meth:`rjust` method of string objects, which
|
||||
right-justifies a string in a field of a given width by padding it with spaces
|
||||
|
@ -165,6 +165,8 @@ shown here::
|
|||
This is particularly useful in combination with the new built-in :func:`vars`
|
||||
function, which returns a dictionary containing all local variables.
|
||||
|
||||
The :mod:`string` module contains a class Template which offers yet another way
|
||||
to substitute values into strings.
|
||||
|
||||
.. _tut-files:
|
||||
|
||||
|
@ -183,7 +185,7 @@ arguments: ``open(filename, mode)``.
|
|||
::
|
||||
|
||||
>>> f=open('/tmp/workfile', 'w')
|
||||
>>> print f
|
||||
>>> print(f)
|
||||
<open file '/tmp/workfile', mode 'w' at 80a0960>
|
||||
|
||||
The first argument is a string containing the filename. The second argument is
|
||||
|
@ -254,7 +256,7 @@ An alternate approach to reading lines is to loop over the file object. This is
|
|||
memory efficient, fast, and leads to simpler code::
|
||||
|
||||
>>> for line in f:
|
||||
print line,
|
||||
print(line, end='')
|
||||
|
||||
This is the first line of the file.
|
||||
Second line of the file
|
||||
|
|
|
@ -158,6 +158,8 @@ token is required next). The completion mechanism might use the interpreter's
|
|||
symbol table. A command to check (or even suggest) matching parentheses,
|
||||
quotes, etc., would also be useful.
|
||||
|
||||
.. %
|
||||
Do we mention IPython? DUBOIS
|
||||
|
||||
.. rubric:: Footnotes
|
||||
|
||||
|
|
|
@ -59,11 +59,30 @@ operators ``+``, ``-``, ``*`` and ``/`` work just like in most other languages
|
|||
>>> 2+2 # and a comment on the same line as code
|
||||
4
|
||||
>>> (50-5*6)/4
|
||||
5
|
||||
5.0
|
||||
>>> 8/5 # Fractions aren't lost when dividing integers
|
||||
1.6000000000000001
|
||||
|
||||
Note: You might not see exactly the same result; floating point results can
|
||||
differ from one machine to another. We will say more later about controlling
|
||||
the appearance of floating point output; what we see here is the most
|
||||
informative display but not as easy to read as we would get with::
|
||||
|
||||
>>> print(8/5)
|
||||
1.6
|
||||
|
||||
For clarity in this tutorial we will show the simpler floating point output
|
||||
unless we are specifically discussing output formatting, and explain later
|
||||
why these two ways of displaying floating point data come to be different.
|
||||
See :ref:`tut-fp-issues` for a full discussion.
|
||||
|
||||
To do integer division and get an integer result,
|
||||
discarding any fractional result, there is another operator, ``//``::
|
||||
|
||||
>>> # Integer division returns the floor:
|
||||
... 7/3
|
||||
... 7//3
|
||||
2
|
||||
>>> 7/-3
|
||||
>>> 7//-3
|
||||
-3
|
||||
|
||||
The equal sign (``'='``) is used to assign a value to a variable. Afterwards, no
|
||||
|
@ -176,6 +195,13 @@ several ways. They can be enclosed in single quotes or double quotes::
|
|||
>>> '"Isn\'t," she said.'
|
||||
'"Isn\'t," she said.'
|
||||
|
||||
The interpreter prints the result of string operations in the same way as they
|
||||
are typed for input: inside quotes, and with quotes and other funny characters
|
||||
escaped by backslashes, to show the precise value. The string is enclosed in
|
||||
double quotes if the string contains a single quote and no double quotes, else
|
||||
it's enclosed in single quotes. Once again, the :func:`print` function
|
||||
produces the more readable output.
|
||||
|
||||
String literals can span multiple lines in several ways. Continuation lines can
|
||||
be used, with a backslash as the last character on the line indicating that the
|
||||
next line is a logical continuation of the line::
|
||||
|
@ -185,7 +211,7 @@ next line is a logical continuation of the line::
|
|||
Note that whitespace at the beginning of the line is\
|
||||
significant."
|
||||
|
||||
print hello
|
||||
print(hello)
|
||||
|
||||
Note that newlines still need to be embedded in the string using ``\n``; the
|
||||
newline following the trailing backslash is discarded. This example would print
|
||||
|
@ -203,7 +229,7 @@ the example::
|
|||
hello = r"This is a rather long string containing\n\
|
||||
several lines of text much as you would do in C."
|
||||
|
||||
print hello
|
||||
print(hello)
|
||||
|
||||
would print::
|
||||
|
||||
|
@ -214,11 +240,11 @@ Or, strings can be surrounded in a pair of matching triple-quotes: ``"""`` or
|
|||
``'''``. End of lines do not need to be escaped when using triple-quotes, but
|
||||
they will be included in the string. ::
|
||||
|
||||
print """
|
||||
print("""
|
||||
Usage: thingy [OPTIONS]
|
||||
-h Display this usage message
|
||||
-H hostname Hostname to connect to
|
||||
"""
|
||||
""")
|
||||
|
||||
produces the following output::
|
||||
|
||||
|
@ -226,12 +252,6 @@ produces the following output::
|
|||
-h Display this usage message
|
||||
-H hostname Hostname to connect to
|
||||
|
||||
The interpreter prints the result of string operations in the same way as they
|
||||
are typed for input: inside quotes, and with quotes and other funny characters
|
||||
escaped by backslashes, to show the precise value. The string is enclosed in
|
||||
double quotes if the string contains a single quote and no double quotes, else
|
||||
it's enclosed in single quotes. (The :keyword:`print` statement, described
|
||||
later, can be used to write strings without quotes or escapes.)
|
||||
|
||||
Strings can be concatenated (glued together) with the ``+`` operator, and
|
||||
repeated with ``*``::
|
||||
|
@ -258,7 +278,7 @@ with two literals, not with arbitrary string expressions::
|
|||
|
||||
Strings can be subscripted (indexed); like in C, the first character of a string
|
||||
has subscript (index) 0. There is no separate character type; a character is
|
||||
simply a string of size one. Like in Icon, substrings can be specified with the
|
||||
simply a string of size one. As in Icon, substrings can be specified with the
|
||||
*slice notation*: two indices separated by a colon. ::
|
||||
|
||||
>>> word[4]
|
||||
|
@ -282,11 +302,11 @@ position in the string results in an error::
|
|||
>>> word[0] = 'x'
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in ?
|
||||
TypeError: object doesn't support item assignment
|
||||
TypeError: 'str' object doesn't support item assignment
|
||||
>>> word[:1] = 'Splat'
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in ?
|
||||
TypeError: object doesn't support slice assignment
|
||||
TypeError: 'str' object doesn't support slice assignment
|
||||
|
||||
However, creating a new string with the combined content is easy and efficient::
|
||||
|
||||
|
@ -371,31 +391,28 @@ The built-in function :func:`len` returns the length of a string::
|
|||
.. seealso::
|
||||
|
||||
:ref:`typesseq`
|
||||
Strings, and the Unicode strings described in the next section, are
|
||||
examples of *sequence types*, and support the common operations supported
|
||||
by such types.
|
||||
Strings are examples of *sequence types*, and support the common
|
||||
operations supported by such types.
|
||||
|
||||
:ref:`string-methods`
|
||||
Both strings and Unicode strings support a large number of methods for
|
||||
Strings support a large number of methods for
|
||||
basic transformations and searching.
|
||||
|
||||
:ref:`string-formatting`
|
||||
The formatting operations invoked when strings and Unicode strings are the
|
||||
The formatting operations invoked when strings are the
|
||||
left operand of the ``%`` operator are described in more detail here.
|
||||
|
||||
|
||||
.. _tut-unicodestrings:
|
||||
|
||||
Unicode Strings
|
||||
---------------
|
||||
About Unicode
|
||||
-------------
|
||||
|
||||
.. sectionauthor:: Marc-Andre Lemburg <mal@lemburg.com>
|
||||
|
||||
|
||||
Starting with Python 2.0 a new data type for storing text data is available to
|
||||
the programmer: the Unicode object. It can be used to store and manipulate
|
||||
Unicode data (see http://www.unicode.org/) and integrates well with the existing
|
||||
string objects, providing auto-conversions where necessary.
|
||||
Starting with Python 3.0 all strings support Unicode.
|
||||
(See http://www.unicode.org/)
|
||||
|
||||
Unicode has the advantage of providing one ordinal for every character in every
|
||||
script used in modern and ancient texts. Previously, there were only 256
|
||||
|
@ -405,19 +422,12 @@ confusion especially with respect to internationalization (usually written as
|
|||
``i18n`` --- ``'i'`` + 18 characters + ``'n'``) of software. Unicode solves
|
||||
these problems by defining one code page for all scripts.
|
||||
|
||||
Creating Unicode strings in Python is just as simple as creating normal
|
||||
strings::
|
||||
|
||||
>>> u'Hello World !'
|
||||
u'Hello World !'
|
||||
|
||||
The small ``'u'`` in front of the quote indicates that a Unicode string is
|
||||
supposed to be created. If you want to include special characters in the string,
|
||||
If you want to include special characters in a string,
|
||||
you can do so by using the Python *Unicode-Escape* encoding. The following
|
||||
example shows how::
|
||||
|
||||
>>> u'Hello\u0020World !'
|
||||
u'Hello World !'
|
||||
>>> 'Hello\u0020World !'
|
||||
'Hello World !'
|
||||
|
||||
The escape sequence ``\u0020`` indicates to insert the Unicode character with
|
||||
the ordinal value 0x0020 (the space character) at the given position.
|
||||
|
@ -428,59 +438,17 @@ Latin-1 encoding that is used in many Western countries, you will find it
|
|||
convenient that the lower 256 characters of Unicode are the same as the 256
|
||||
characters of Latin-1.
|
||||
|
||||
For experts, there is also a raw mode just like the one for normal strings. You
|
||||
have to prefix the opening quote with 'ur' to have Python use the
|
||||
*Raw-Unicode-Escape* encoding. It will only apply the above ``\uXXXX``
|
||||
conversion if there is an uneven number of backslashes in front of the small
|
||||
'u'. ::
|
||||
|
||||
>>> ur'Hello\u0020World !'
|
||||
u'Hello World !'
|
||||
>>> ur'Hello\\u0020World !'
|
||||
u'Hello\\\\u0020World !'
|
||||
|
||||
The raw mode is most useful when you have to enter lots of backslashes, as can
|
||||
be necessary in regular expressions.
|
||||
|
||||
Apart from these standard encodings, Python provides a whole set of other ways
|
||||
of creating Unicode strings on the basis of a known encoding.
|
||||
|
||||
.. index:: builtin: unicode
|
||||
|
||||
The built-in function :func:`unicode` provides access to all registered Unicode
|
||||
codecs (COders and DECoders). Some of the more well known encodings which these
|
||||
codecs can convert are *Latin-1*, *ASCII*, *UTF-8*, and *UTF-16*. The latter two
|
||||
are variable-length encodings that store each Unicode character in one or more
|
||||
bytes. The default encoding is normally set to ASCII, which passes through
|
||||
characters in the range 0 to 127 and rejects any other characters with an error.
|
||||
When a Unicode string is printed, written to a file, or converted with
|
||||
:func:`str`, conversion takes place using this default encoding. ::
|
||||
|
||||
>>> u"abc"
|
||||
u'abc'
|
||||
>>> str(u"abc")
|
||||
'abc'
|
||||
>>> u"äöü"
|
||||
u'\xe4\xf6\xfc'
|
||||
>>> str(u"äöü")
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in ?
|
||||
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
|
||||
|
||||
To convert a Unicode string into an 8-bit string using a specific encoding,
|
||||
Unicode objects provide an :func:`encode` method that takes one argument, the
|
||||
To convert a string into a sequence of bytes using a specific encoding,
|
||||
string objects provide an :func:`encode` method that takes one argument, the
|
||||
name of the encoding. Lowercase names for encodings are preferred. ::
|
||||
|
||||
>>> u"äöü".encode('utf-8')
|
||||
'\xc3\xa4\xc3\xb6\xc3\xbc'
|
||||
|
||||
If you have data in a specific encoding and want to produce a corresponding
|
||||
Unicode string from it, you can use the :func:`unicode` function with the
|
||||
encoding name as the second argument. ::
|
||||
|
||||
>>> unicode('\xc3\xa4\xc3\xb6\xc3\xbc', 'utf-8')
|
||||
u'\xe4\xf6\xfc'
|
||||
>>> "äÃ\u0020Ã".encode('utf-8')
|
||||
b'A*A A'
|
||||
|
||||
.. % above example needs beefing up by a unicode dude
|
||||
|
||||
.. _tut-lists:
|
||||
|
||||
|
@ -561,7 +529,10 @@ example::
|
|||
[2, 3]
|
||||
>>> p[1][0]
|
||||
2
|
||||
>>> p[1].append('xtra') # See section 5.1
|
||||
|
||||
You can add something to the end of the list::
|
||||
|
||||
>>> p[1].append('xtra')
|
||||
>>> p
|
||||
[1, [2, 3, 'xtra'], 4]
|
||||
>>> q
|
||||
|
@ -584,7 +555,7 @@ series as follows::
|
|||
... # the sum of two elements defines the next
|
||||
... a, b = 0, 1
|
||||
>>> while b < 10:
|
||||
... print b
|
||||
... print(b)
|
||||
... a, b = b, a+b
|
||||
...
|
||||
1
|
||||
|
@ -620,26 +591,29 @@ This example introduces several new features.
|
|||
completion (since the parser cannot guess when you have typed the last line).
|
||||
Note that each line within a basic block must be indented by the same amount.
|
||||
|
||||
* The :keyword:`print` statement writes the value of the expression(s) it is
|
||||
* The :func:`print` function writes the value of the expression(s) it is
|
||||
given. It differs from just writing the expression you want to write (as we did
|
||||
earlier in the calculator examples) in the way it handles multiple expressions
|
||||
earlier in the calculator examples) in the way it handles multiple
|
||||
expressions, floating point quantities,
|
||||
and strings. Strings are printed without quotes, and a space is inserted
|
||||
between items, so you can format things nicely, like this::
|
||||
|
||||
>>> i = 256*256
|
||||
>>> print 'The value of i is', i
|
||||
>>> print('The value of i is', i)
|
||||
The value of i is 65536
|
||||
|
||||
A trailing comma avoids the newline after the output::
|
||||
The keyword end can be used to avoid the newline after the output::
|
||||
|
||||
>>> a, b = 0, 1
|
||||
>>> while b < 1000:
|
||||
... print b,
|
||||
... print(b, ' ', end='')
|
||||
... a, b = b, a+b
|
||||
...
|
||||
>>> print()
|
||||
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
|
||||
|
||||
Note that the interpreter inserts a newline before it prints the next prompt if
|
||||
the last line was not completed.
|
||||
Note that nothing appeared after the loop ended, until we printed
|
||||
a newline.
|
||||
|
||||
|
||||
|
||||
|
|
|
@ -30,7 +30,7 @@ called :file:`fibo.py` in the current directory with the following contents::
|
|||
def fib(n): # write Fibonacci series up to n
|
||||
a, b = 0, 1
|
||||
while b < n:
|
||||
print b,
|
||||
print(b, end=' ')
|
||||
a, b = b, a+b
|
||||
|
||||
def fib2(n): # return Fibonacci series up to n
|
||||
|
@ -102,6 +102,9 @@ There is even a variant to import all names that a module defines::
|
|||
1 1 2 3 5 8 13 21 34 55 89 144 233 377
|
||||
|
||||
This imports all names except those beginning with an underscore (``_``).
|
||||
In most cases Python programmers do not use this facility since it introduces
|
||||
an unknown set of names into the interpreter, possibly hiding some things
|
||||
you have already defined.
|
||||
|
||||
|
||||
.. _tut-modulesasscripts:
|
||||
|
@ -162,6 +165,8 @@ the same name as a standard module, or Python will attempt to load the script as
|
|||
a module when that module is imported. This will generally be an error. See
|
||||
section :ref:`tut-standardmodules` for more information.
|
||||
|
||||
.. %
|
||||
Do we need stuff on zip files etc. ? DUBOIS
|
||||
|
||||
"Compiled" Python files
|
||||
-----------------------
|
||||
|
@ -218,7 +223,10 @@ Some tips for experts:
|
|||
* The module :mod:`compileall` can create :file:`.pyc` files (or :file:`.pyo`
|
||||
files when :option:`-O` is used) for all modules in a directory.
|
||||
|
||||
.. %
|
||||
* If using Python in a parallel processing system with a shared file system,
|
||||
you need to patch python to disable the creation of the compiled files
|
||||
because otherwise the multiple Python interpreters will encounter race
|
||||
conditions in creating them.
|
||||
|
||||
|
||||
.. _tut-standardmodules:
|
||||
|
@ -250,7 +258,7 @@ prompts:
|
|||
>>> sys.ps2
|
||||
'... '
|
||||
>>> sys.ps1 = 'C> '
|
||||
C> print 'Yuck!'
|
||||
C> print('Yuck!')
|
||||
Yuck!
|
||||
C>
|
||||
|
||||
|
@ -308,31 +316,27 @@ want a list of those, they are defined in the standard module
|
|||
|
||||
>>> import __builtin__
|
||||
>>> dir(__builtin__)
|
||||
['ArithmeticError', 'AssertionError', 'AttributeError', 'DeprecationWarning',
|
||||
'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
|
||||
'FloatingPointError', 'FutureWarning', 'IOError', 'ImportError',
|
||||
'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
|
||||
'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented',
|
||||
'NotImplementedError', 'OSError', 'OverflowError',
|
||||
'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError',
|
||||
'RuntimeWarning', 'StopIteration', 'SyntaxError',
|
||||
'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True',
|
||||
'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',
|
||||
'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',
|
||||
'UserWarning', 'ValueError', 'Warning', 'WindowsError',
|
||||
'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__',
|
||||
'__name__', 'abs', 'basestring', 'bool', 'buffer',
|
||||
'chr', 'classmethod', 'cmp', 'compile',
|
||||
'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod',
|
||||
'enumerate', 'eval', 'exec', 'exit', 'filter', 'float',
|
||||
'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex',
|
||||
'id', 'input', 'int', 'isinstance', 'issubclass', 'iter',
|
||||
'len', 'license', 'list', 'locals', 'map', 'max', 'min',
|
||||
'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range',
|
||||
'repr', 'reversed', 'round', 'set',
|
||||
'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',
|
||||
'tuple', 'type', 'vars', 'zip']
|
||||
|
||||
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'Buffer
|
||||
Error', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Excep
|
||||
tion', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError
|
||||
', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError',
|
||||
'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImp
|
||||
lemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecatio
|
||||
nWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StopIteration',
|
||||
'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True',
|
||||
'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', '
|
||||
UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueE
|
||||
rror', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__'
|
||||
, '__import__', '__name__', 'abs', 'all', 'any', 'basestring', 'bin', 'bool', 'b
|
||||
uffer', 'bytes', 'chr', 'chr8', 'classmethod', 'cmp', 'compile', 'complex', 'cop
|
||||
yright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'ex
|
||||
ec', 'exit', 'filter', 'float', 'frozenset', 'getattr', 'globals', 'hasattr', 'h
|
||||
ash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', '
|
||||
len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'o
|
||||
bject', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr
|
||||
', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'st
|
||||
r', 'str8', 'sum', 'super', 'trunc', 'tuple', 'type', 'vars', 'zip']
|
||||
|
||||
.. _tut-packages:
|
||||
|
||||
|
|
|
@ -67,7 +67,7 @@ instance the following output results from running ``python demo.py one two
|
|||
three`` at the command line::
|
||||
|
||||
>>> import sys
|
||||
>>> print sys.argv
|
||||
>>> print(sys.argv)
|
||||
['demo.py', 'one', 'two', 'three']
|
||||
|
||||
The :mod:`getopt` module processes *sys.argv* using the conventions of the Unix
|
||||
|
@ -138,6 +138,8 @@ The :mod:`random` module provides tools for making random selections::
|
|||
>>> random.randrange(6) # random integer chosen from range(6)
|
||||
4
|
||||
|
||||
The SciPy project <http://scipy.org> has many other modules for numerical
|
||||
computations.
|
||||
|
||||
.. _tut-internet-access:
|
||||
|
||||
|
@ -151,7 +153,7 @@ and :mod:`smtplib` for sending mail::
|
|||
>>> import urllib2
|
||||
>>> for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
|
||||
... if 'EST' in line or 'EDT' in line: # look for Eastern Time
|
||||
... print line
|
||||
... print(line)
|
||||
|
||||
<BR>Nov. 25, 09:43:32 PM EST
|
||||
|
||||
|
@ -259,7 +261,7 @@ documentation::
|
|||
def average(values):
|
||||
"""Computes the arithmetic mean of a list of numbers.
|
||||
|
||||
>>> print average([20, 30, 70])
|
||||
>>> print(average([20, 30, 70]))
|
||||
40.0
|
||||
"""
|
||||
return sum(values, 0.0) / len(values)
|
||||
|
|
|
@ -184,14 +184,14 @@ tasks in background while the main program continues to run::
|
|||
f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
|
||||
f.write(self.infile)
|
||||
f.close()
|
||||
print 'Finished background zip of: ', self.infile
|
||||
print('Finished background zip of: ', self.infile)
|
||||
|
||||
background = AsyncZip('mydata.txt', 'myarchive.zip')
|
||||
background.start()
|
||||
print 'The main program continues to run in foreground.'
|
||||
print('The main program continues to run in foreground.')
|
||||
|
||||
background.join() # Wait for the background task to finish
|
||||
print 'Main program waited until background was done.'
|
||||
print('Main program waited until background was done.')
|
||||
|
||||
The principal challenge of multi-threaded applications is coordinating threads
|
||||
that share data or other resources. To that end, the threading module provides
|
||||
|
@ -309,7 +309,7 @@ tree searches::
|
|||
>>> from collections import deque
|
||||
>>> d = deque(["task1", "task2", "task3"])
|
||||
>>> d.append("task4")
|
||||
>>> print "Handling", d.popleft()
|
||||
>>> print("Handling", d.popleft())
|
||||
Handling task1
|
||||
|
||||
unsearched = deque([starting_node])
|
||||
|
|
|
@ -48,6 +48,11 @@ More Python resources:
|
|||
Particularly notable contributions are collected in a book also titled Python
|
||||
Cookbook (O'Reilly & Associates, ISBN 0-596-00797-3.)
|
||||
|
||||
* http://scipy.org: The Scientific Python project includes modules for fast
|
||||
array computations and manipulations plus a host of packages for such
|
||||
things as linear algebra, Fourier transforms, non-linear solvers,
|
||||
random number distributions, statistical analysis and the like.
|
||||
|
||||
For Python-related questions and problem reports, you can post to the newsgroup
|
||||
:newsgroup:`comp.lang.python`, or send them to the mailing list at
|
||||
python-list@python.org. The newsgroup and mailing list are gatewayed, so
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue