rest25/tutorial/introduction.rst => rest262/tutorial/introduction.rst
6
7In the following examples, input and output are distinguished by the presence or
8absence of prompts (``>>>`` and ``...``): to repeat the example, you must type
9everything after the prompt, when the prompt appears; lines that do not begin
10with a prompt are output from the interpreter. Note that a secondary prompt on a
11line by itself in an example means you must type a blank line; this is used to
12end a multi-line command.
13
n14-.. % 
15-.. % \footnote{
16-.. % I'd prefer to use different fonts to distinguish input
17-.. % from output, but the amount of LaTeX hacking that would require
18-.. % is currently beyond my ability.
19-.. % }
20- 
21Many of the examples in this manual, even those entered at the interactive
22prompt, include comments.  Comments in Python start with the hash character,
n23-``'#'``, and extend to the end of the physical line.  A comment may appear at
n16+``#``, and extend to the end of the physical line.  A comment may appear at the
24-the start of a line or following whitespace or code, but not within a string
17+start of a line or following whitespace or code, but not within a string
25-literal.  A hash  character within a string literal is just a hash character.
18+literal.  A hash character within a string literal is just a hash character.
19+Since comments are to clarify code and are not interpreted by Python, they may
20+be omitted when typing in examples.
26
27Some examples::
28
29   # this is the first comment
30   SPAM = 1                 # and this is the second comment
31                            # ... and now a third!
32   STRING = "# This is not a comment."
33
79   >>> x = y = z = 0  # Zero x, y and z
80   >>> x
81   0
82   >>> y
83   0
84   >>> z
85   0
86
n82+Variables must be "defined" (assigned a value) before they can be used, or an
83+error will occur::
84+ 
85+   >>> # try to access an undefined variable
86+   ... n
87+   Traceback (most recent call last):
88+     File "<stdin>", line 1, in <module>
89+   NameError: name 'n' is not defined
90+ 
87There is full support for floating point; operators with mixed type operands
88convert the integer operand to floating point::
89
90   >>> 3 * 3.75 / 1.5
91   7.5
92   >>> 7.0 / 2
93   3.5
94
190Note that newlines still need to be embedded in the string using ``\n``; the
191newline following the trailing backslash is discarded.  This example would print
192the following::
193
194   This is a rather long string containing
195   several lines of text just as you would do in C.
196       Note that whitespace at the beginning of the line is significant.
197
n198-If we make the string literal a "raw" string, however, the ``\n`` sequences are
199-not converted to newlines, but the backslash at the end of the line, and the
200-newline character in the source, are both included in the string as data.  Thus,
201-the example::
202- 
203-   hello = r"This is a rather long string containing\n\
204-   several lines of text much as you would do in C."
205- 
206-   print hello
207- 
208-would print::
209- 
210-   This is a rather long string containing\n\
211-   several lines of text much as you would do in C.
212- 
213Or, strings can be surrounded in a pair of matching triple-quotes: ``"""`` or
214``'''``.  End of lines do not need to be escaped when using triple-quotes, but
215they will be included in the string. ::
216
217   print """
n218-   Usage: thingy [OPTIONS] 
n207+   Usage: thingy [OPTIONS]
219        -h                        Display this usage message
220        -H hostname               Hostname to connect to
221   """
222
223produces the following output::
224
n225-   Usage: thingy [OPTIONS] 
n214+   Usage: thingy [OPTIONS]
226        -h                        Display this usage message
227        -H hostname               Hostname to connect to
n217+ 
218+If we make the string literal a "raw" string, ``\n`` sequences are not converted
219+to newlines, but the backslash at the end of the line, and the newline character
220+in the source, are both included in the string as data.  Thus, the example::
221+ 
222+   hello = r"This is a rather long string containing\n\
223+   several lines of text much as you would do in C."
224+ 
225+   print hello
226+ 
227+would print::
228+ 
229+   This is a rather long string containing\n\
230+   several lines of text much as you would do in C.
228
229The interpreter prints the result of string operations in the same way as they
230are typed for input: inside quotes, and with quotes and other funny characters
231escaped by backslashes, to show the precise value.  The string is enclosed in
232double quotes if the string contains a single quote and no double quotes, else
233it's enclosed in single quotes.  (The :keyword:`print` statement, described
234later, can be used to write strings without quotes or escapes.)
235
271Slice indices have useful defaults; an omitted first index defaults to zero, an
272omitted second index defaults to the size of the string being sliced. ::
273
274   >>> word[:2]    # The first two characters
275   'He'
276   >>> word[2:]    # Everything except the first two characters
277   'lpA'
278
n279-Unlike a C string, Python strings cannot be changed.  Assigning to an  indexed
n282+Unlike a C string, Python strings cannot be changed.  Assigning to an indexed
280position in the string results in an error::
281
282   >>> word[0] = 'x'
283   Traceback (most recent call last):
284     File "<stdin>", line 1, in ?
285   TypeError: object doesn't support item assignment
286   >>> word[:1] = 'Splat'
287   Traceback (most recent call last):
336
337   >>> word[-100:]
338   'HelpA'
339   >>> word[-10]    # error
340   Traceback (most recent call last):
341     File "<stdin>", line 1, in ?
342   IndexError: string index out of range
343
n344-The best way to remember how slices work is to think of the indices as pointing
n347+One way to remember how slices work is to think of the indices as pointing
345*between* characters, with the left edge of the first character numbered 0.
346Then the right edge of the last character of a string of *n* characters has
347index *n*, for example::
348
n349-    +---+---+---+---+---+ 
n352+    +---+---+---+---+---+
350    | H | e | l | p | A |
n351-    +---+---+---+---+---+ 
n354+    +---+---+---+---+---+
352-    0   1   2   3   4   5 
355+    0   1   2   3   4   5
353   -5  -4  -3  -2  -1
354
355The first row of numbers gives the position of the indices 0...5 in the string;
356the second row gives the corresponding negative indices. The slice from *i* to
357*j* consists of all characters between the edges labeled *i* and *j*,
358respectively.
359
360For non-negative indices, the length of a slice is the difference of the
365
366   >>> s = 'supercalifragilisticexpialidocious'
367   >>> len(s)
368   34
369
370
371.. seealso::
372
n373-   `Sequence Types <../lib/typesseq.html>`_
n376+   :ref:`typesseq`
374-      Strings, and the Unicode strings described in the next section, are examples of
377+      Strings, and the Unicode strings described in the next section, are
375-      *sequence types*, and support the common operations supported by such types.
378+      examples of *sequence types*, and support the common operations supported
379+      by such types.
376
n377-   `String Methods <../lib/string-methods.html>`_
n381+   :ref:`string-methods`
378-      Both strings and Unicode strings support a large number of methods for basic
382+      Both strings and Unicode strings support a large number of methods for
379-      transformations and searching.
383+      basic transformations and searching.
380
n381-   `String Formatting Operations <../lib/typesseq-strings.html>`_
n385+   :ref:`new-string-formatting`
386+      Information about string formatting with :meth:`str.format` is described
387+      here.
388+ 
389+   :ref:`string-formatting`
382-      The formatting operations invoked when strings and Unicode strings are the left
390+      The old formatting operations invoked when strings and Unicode strings are
383-      operand of the ``%`` operator are described in more detail here.
391+      the left operand of the ``%`` operator are described in more detail here.
384
385
386.. _tut-unicodestrings:
387
388Unicode Strings
389---------------
390
391.. sectionauthor:: Marc-Andre Lemburg <mal@lemburg.com>
392
393
394Starting with Python 2.0 a new data type for storing text data is available to
395the programmer: the Unicode object. It can be used to store and manipulate
n396-Unicode data (see `<http://www.unicode.org/>`_) and integrates well with the
n404+Unicode data (see http://www.unicode.org/) and integrates well with the existing
397-existing string objects, providing auto-conversions where necessary.
405+string objects, providing auto-conversions where necessary.
398
399Unicode has the advantage of providing one ordinal for every character in every
400script used in modern and ancient texts. Previously, there were only 256
401possible ordinals for script characters. Texts were typically bound to a code
402page which mapped the ordinals to script characters. This lead to very much
403confusion especially with respect to internationalization (usually written as
404``i18n`` --- ``'i'`` + 18 characters + ``'n'``) of software.  Unicode solves
405these problems by defining one code page for all scripts.
423
424Other characters are interpreted by using their respective ordinal values
425directly as Unicode ordinals.  If you have literal strings in the standard
426Latin-1 encoding that is used in many Western countries, you will find it
427convenient that the lower 256 characters of Unicode are the same as the 256
428characters of Latin-1.
429
430For experts, there is also a raw mode just like the one for normal strings. You
n431-have to prefix the opening quote with 'ur' to have Python use the *Raw-Unicode-
n439+have to prefix the opening quote with 'ur' to have Python use the
432-Escape* encoding. It will only apply the above ``\uXXXX`` conversion if there is
440+*Raw-Unicode-Escape* encoding. It will only apply the above ``\uXXXX``
433-an uneven number of backslashes in front of the small 'u'. ::
441+conversion if there is an uneven number of backslashes in front of the small
442+'u'. ::
434
435   >>> ur'Hello\u0020World !'
436   u'Hello World !'
437   >>> ur'Hello\\u0020World !'
438   u'Hello\\\\u0020World !'
439
440The raw mode is most useful when you have to enter lots of backslashes, as can
441be necessary in regular expressions.
540   [123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
541   >>> # Clear the list: replace all items with an empty list
542   >>> a[:] = []
543   >>> a
544   []
545
546The built-in function :func:`len` also applies to lists::
547
n557+   >>> a = ['a', 'b', 'c', 'd']
548   >>> len(a)
n549-   8
n559+   4
550
551It is possible to nest lists (create lists containing other lists), for
552example::
553
554   >>> q = [2, 3]
555   >>> p = [1, q, 4]
556   >>> len(p)
557   3
577Of course, we can use Python for more complicated tasks than adding two and two
578together.  For instance, we can write an initial sub-sequence of the *Fibonacci*
579series as follows::
580
581   >>> # Fibonacci series:
582   ... # the sum of two elements defines the next
583   ... a, b = 0, 1
584   >>> while b < 10:
n585-   ...       print b
n595+   ...     print b
586-   ...       a, b = b, a+b
596+   ...     a, b = b, a+b
587-   ... 
597+   ...
588   1
589   1
590   2
591   3
592   5
593   8
594
595This example introduces several new features.
629     The value of i is 65536
630
631  A trailing comma avoids the newline after the output::
632
633     >>> a, b = 0, 1
634     >>> while b < 1000:
635     ...     print b,
636     ...     a, b = b, a+b
n637-     ... 
n647+     ...
638     1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
639
640  Note that the interpreter inserts a newline before it prints the next prompt if
641  the last line was not completed.
t642- 
643- 
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op