cpython/Doc/tutorial/introduction.rst

617 lines
19 KiB
ReStructuredText
Raw Normal View History

2007-08-15 11:28:22 -03:00
.. _tut-informal:
**********************************
An Informal Introduction to Python
**********************************
In the following examples, input and output are distinguished by the presence or
absence of prompts (``>>>`` and ``...``): to repeat the example, you must type
everything after the prompt, when the prompt appears; lines that do not begin
with a prompt are output from the interpreter. Note that a secondary prompt on a
line by itself in an example means you must type a blank line; this is used to
end a multi-line command.
Many of the examples in this manual, even those entered at the interactive
prompt, include comments. Comments in Python start with the hash character,
2008-09-13 14:18:21 -03:00
``#``, and extend to the end of the physical line. A comment may appear at the
start of a line or following whitespace or code, but not within a string
literal. A hash character within a string literal is just a hash character.
2008-09-13 14:18:21 -03:00
Since comments are to clarify code and are not interpreted by Python, they may
be omitted when typing in examples.
2007-08-15 11:28:22 -03:00
Some examples::
# this is the first comment
SPAM = 1 # and this is the second comment
# ... and now a third!
STRING = "# This is not a comment."
.. _tut-calculator:
Using Python as a Calculator
============================
Let's try some simple Python commands. Start the interpreter and wait for the
primary prompt, ``>>>``. (It shouldn't take long.)
.. _tut-numbers:
Numbers
-------
The interpreter acts as a simple calculator: you can type an expression at it
and it will write the value. Expression syntax is straightforward: the
operators ``+``, ``-``, ``*`` and ``/`` work just like in most other languages
(for example, Pascal or C); parentheses can be used for grouping. For example::
>>> 2+2
4
>>> # This is a comment
... 2+2
4
>>> 2+2 # and a comment on the same line as code
4
>>> (50-5*6)/4
5.0
>>> 8/5 # Fractions aren't lost when dividing integers
1.6
2009-01-03 17:18:54 -04:00
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. See also :ref:`tut-fp-issues` for a
full discussion of some of the subtleties of floating point numbers and their
representations.
2009-01-03 17:18:54 -04:00
To do integer division and get an integer result,
discarding any fractional result, there is another operator, ``//``::
2009-01-03 17:18:54 -04:00
2007-08-15 11:28:22 -03:00
>>> # Integer division returns the floor:
... 7//3
2007-08-15 11:28:22 -03:00
2
>>> 7//-3
2007-08-15 11:28:22 -03:00
-3
The equal sign (``'='``) is used to assign a value to a variable. Afterwards, no
result is displayed before the next interactive prompt::
>>> width = 20
>>> height = 5*9
>>> width * height
900
A value can be assigned to several variables simultaneously::
>>> x = y = z = 0 # Zero x, y and z
>>> x
0
>>> y
0
>>> z
0
2008-09-13 14:18:21 -03:00
Variables must be "defined" (assigned a value) before they can be used, or an
error will occur::
>>> # try to access an undefined variable
... n
2009-01-03 17:18:54 -04:00
Traceback (most recent call last):
2008-09-13 14:18:21 -03:00
File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
2007-08-15 11:28:22 -03:00
There is full support for floating point; operators with mixed type operands
convert the integer operand to floating point::
>>> 3 * 3.75 / 1.5
7.5
>>> 7.0 / 2
3.5
Complex numbers are also supported; imaginary numbers are written with a suffix
of ``j`` or ``J``. Complex numbers with a nonzero real component are written as
``(real+imagj)``, or can be created with the ``complex(real, imag)`` function.
::
>>> 1j * 1J
(-1+0j)
>>> 1j * complex(0, 1)
2007-08-15 11:28:22 -03:00
(-1+0j)
>>> 3+1j*3
(3+3j)
>>> (3+1j)*3
(9+3j)
>>> (1+2j)/(1+1j)
(1.5+0.5j)
Complex numbers are always represented as two floating point numbers, the real
and imaginary part. To extract these parts from a complex number *z*, use
``z.real`` and ``z.imag``. ::
>>> a=1.5+0.5j
>>> a.real
1.5
>>> a.imag
0.5
The conversion functions to floating point and integer (:func:`float`,
:func:`int`) don't work for complex numbers --- there is not one correct way to
convert a complex number to a real number. Use ``abs(z)`` to get its magnitude
(as a float) or ``z.real`` to get its real part::
2007-08-15 11:28:22 -03:00
>>> a=3.0+4.0j
>>> float(a)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: can't convert complex to float; use abs(z)
>>> a.real
3.0
>>> a.imag
4.0
>>> abs(a) # sqrt(a.real**2 + a.imag**2)
5.0
In interactive mode, the last printed expression is assigned to the variable
``_``. This means that when you are using Python as a desk calculator, it is
somewhat easier to continue calculations, for example::
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
This variable should be treated as read-only by the user. Don't explicitly
assign a value to it --- you would create an independent local variable with the
same name masking the built-in variable with its magic behavior.
.. _tut-strings:
Strings
-------
Besides numbers, Python can also manipulate strings, which can be expressed in
several ways. They can be enclosed in single quotes or double quotes::
>>> 'spam eggs'
'spam eggs'
>>> 'doesn\'t'
"doesn't"
>>> "doesn't"
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"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.
2007-08-15 11:28:22 -03:00
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::
hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
Note that whitespace at the beginning of the line is\
significant."
print(hello)
2007-08-15 11:28:22 -03:00
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
Merged revisions 74745 via svnmerge from svn+ssh://pythondev@svn.python.org/python/branches/py3k ................ r74745 | benjamin.peterson | 2009-09-11 17:24:02 -0500 (Fri, 11 Sep 2009) | 98 lines Merged revisions 74277,74321,74323,74326,74355,74465,74467,74488,74492,74513,74531,74549,74553,74625,74632,74643-74644,74647,74652,74666,74671,74727,74739 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r74277 | sean.reifschneider | 2009-08-01 18:54:55 -0500 (Sat, 01 Aug 2009) | 3 lines - Issue #6624: yArg_ParseTuple with "s" format when parsing argument with NUL: Bogus TypeError detail string. ........ r74321 | guilherme.polo | 2009-08-05 11:51:41 -0500 (Wed, 05 Aug 2009) | 1 line Easier reference to find (at least while svn continues being used). ........ r74323 | guilherme.polo | 2009-08-05 18:48:26 -0500 (Wed, 05 Aug 2009) | 1 line Typo. ........ r74326 | jesse.noller | 2009-08-05 21:05:56 -0500 (Wed, 05 Aug 2009) | 1 line Fix issue 4660: spurious task_done errors in multiprocessing, remove doc note for from_address ........ r74355 | gregory.p.smith | 2009-08-12 12:02:37 -0500 (Wed, 12 Aug 2009) | 2 lines comment typo fix ........ r74465 | vinay.sajip | 2009-08-15 18:23:12 -0500 (Sat, 15 Aug 2009) | 1 line Added section on logging to one file from multiple processes. ........ r74467 | vinay.sajip | 2009-08-15 18:34:47 -0500 (Sat, 15 Aug 2009) | 1 line Refined section on logging to one file from multiple processes. ........ r74488 | vinay.sajip | 2009-08-17 08:14:37 -0500 (Mon, 17 Aug 2009) | 1 line Further refined section on logging to one file from multiple processes. ........ r74492 | r.david.murray | 2009-08-17 14:26:49 -0500 (Mon, 17 Aug 2009) | 2 lines Issue 6685: 'toupper' -> 'upper' in cgi doc example explanation. ........ r74513 | skip.montanaro | 2009-08-18 09:37:52 -0500 (Tue, 18 Aug 2009) | 1 line missing module ref (issue6723) ........ r74531 | vinay.sajip | 2009-08-20 17:04:32 -0500 (Thu, 20 Aug 2009) | 1 line Added section on exceptions raised during logging. ........ r74549 | benjamin.peterson | 2009-08-24 12:42:36 -0500 (Mon, 24 Aug 2009) | 1 line fix pdf building by teaching latex the right encoding package ........ r74553 | r.david.murray | 2009-08-26 20:04:59 -0500 (Wed, 26 Aug 2009) | 2 lines Remove leftover text from end of sentence. ........ r74625 | benjamin.peterson | 2009-09-01 17:27:57 -0500 (Tue, 01 Sep 2009) | 1 line remove the check that classmethod's argument is a callable ........ r74632 | georg.brandl | 2009-09-03 02:27:26 -0500 (Thu, 03 Sep 2009) | 1 line #6828: fix wrongly highlighted blocks. ........ r74643 | georg.brandl | 2009-09-04 01:59:20 -0500 (Fri, 04 Sep 2009) | 2 lines Issue #2666: Handle BROWSER environment variable properly for unknown browser names in the webbrowser module. ........ r74644 | georg.brandl | 2009-09-04 02:55:14 -0500 (Fri, 04 Sep 2009) | 1 line #5047: remove Monterey support from configure. ........ r74647 | georg.brandl | 2009-09-04 03:17:04 -0500 (Fri, 04 Sep 2009) | 2 lines Issue #5275: In Cookie's Cookie.load(), properly handle non-string arguments as documented. ........ r74652 | georg.brandl | 2009-09-04 06:25:37 -0500 (Fri, 04 Sep 2009) | 1 line #6756: add some info about the "acct" parameter. ........ r74666 | georg.brandl | 2009-09-05 04:04:09 -0500 (Sat, 05 Sep 2009) | 1 line #6841: remove duplicated word. ........ r74671 | georg.brandl | 2009-09-05 11:47:17 -0500 (Sat, 05 Sep 2009) | 1 line #6843: add link from filterwarnings to where the meaning of the arguments is covered. ........ r74727 | benjamin.peterson | 2009-09-08 18:04:22 -0500 (Tue, 08 Sep 2009) | 1 line #6865 fix ref counting in initialization of pwd module ........ r74739 | georg.brandl | 2009-09-11 02:55:20 -0500 (Fri, 11 Sep 2009) | 1 line Move function back to its section. ........ ................
2009-09-11 19:36:27 -03:00
the following:
.. code-block:: text
2007-08-15 11:28:22 -03:00
This is a rather long string containing
several lines of text just as you would do in C.
Note that whitespace at the beginning of the line is significant.
Merged revisions 74745 via svnmerge from svn+ssh://pythondev@svn.python.org/python/branches/py3k ................ r74745 | benjamin.peterson | 2009-09-11 17:24:02 -0500 (Fri, 11 Sep 2009) | 98 lines Merged revisions 74277,74321,74323,74326,74355,74465,74467,74488,74492,74513,74531,74549,74553,74625,74632,74643-74644,74647,74652,74666,74671,74727,74739 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r74277 | sean.reifschneider | 2009-08-01 18:54:55 -0500 (Sat, 01 Aug 2009) | 3 lines - Issue #6624: yArg_ParseTuple with "s" format when parsing argument with NUL: Bogus TypeError detail string. ........ r74321 | guilherme.polo | 2009-08-05 11:51:41 -0500 (Wed, 05 Aug 2009) | 1 line Easier reference to find (at least while svn continues being used). ........ r74323 | guilherme.polo | 2009-08-05 18:48:26 -0500 (Wed, 05 Aug 2009) | 1 line Typo. ........ r74326 | jesse.noller | 2009-08-05 21:05:56 -0500 (Wed, 05 Aug 2009) | 1 line Fix issue 4660: spurious task_done errors in multiprocessing, remove doc note for from_address ........ r74355 | gregory.p.smith | 2009-08-12 12:02:37 -0500 (Wed, 12 Aug 2009) | 2 lines comment typo fix ........ r74465 | vinay.sajip | 2009-08-15 18:23:12 -0500 (Sat, 15 Aug 2009) | 1 line Added section on logging to one file from multiple processes. ........ r74467 | vinay.sajip | 2009-08-15 18:34:47 -0500 (Sat, 15 Aug 2009) | 1 line Refined section on logging to one file from multiple processes. ........ r74488 | vinay.sajip | 2009-08-17 08:14:37 -0500 (Mon, 17 Aug 2009) | 1 line Further refined section on logging to one file from multiple processes. ........ r74492 | r.david.murray | 2009-08-17 14:26:49 -0500 (Mon, 17 Aug 2009) | 2 lines Issue 6685: 'toupper' -> 'upper' in cgi doc example explanation. ........ r74513 | skip.montanaro | 2009-08-18 09:37:52 -0500 (Tue, 18 Aug 2009) | 1 line missing module ref (issue6723) ........ r74531 | vinay.sajip | 2009-08-20 17:04:32 -0500 (Thu, 20 Aug 2009) | 1 line Added section on exceptions raised during logging. ........ r74549 | benjamin.peterson | 2009-08-24 12:42:36 -0500 (Mon, 24 Aug 2009) | 1 line fix pdf building by teaching latex the right encoding package ........ r74553 | r.david.murray | 2009-08-26 20:04:59 -0500 (Wed, 26 Aug 2009) | 2 lines Remove leftover text from end of sentence. ........ r74625 | benjamin.peterson | 2009-09-01 17:27:57 -0500 (Tue, 01 Sep 2009) | 1 line remove the check that classmethod's argument is a callable ........ r74632 | georg.brandl | 2009-09-03 02:27:26 -0500 (Thu, 03 Sep 2009) | 1 line #6828: fix wrongly highlighted blocks. ........ r74643 | georg.brandl | 2009-09-04 01:59:20 -0500 (Fri, 04 Sep 2009) | 2 lines Issue #2666: Handle BROWSER environment variable properly for unknown browser names in the webbrowser module. ........ r74644 | georg.brandl | 2009-09-04 02:55:14 -0500 (Fri, 04 Sep 2009) | 1 line #5047: remove Monterey support from configure. ........ r74647 | georg.brandl | 2009-09-04 03:17:04 -0500 (Fri, 04 Sep 2009) | 2 lines Issue #5275: In Cookie's Cookie.load(), properly handle non-string arguments as documented. ........ r74652 | georg.brandl | 2009-09-04 06:25:37 -0500 (Fri, 04 Sep 2009) | 1 line #6756: add some info about the "acct" parameter. ........ r74666 | georg.brandl | 2009-09-05 04:04:09 -0500 (Sat, 05 Sep 2009) | 1 line #6841: remove duplicated word. ........ r74671 | georg.brandl | 2009-09-05 11:47:17 -0500 (Sat, 05 Sep 2009) | 1 line #6843: add link from filterwarnings to where the meaning of the arguments is covered. ........ r74727 | benjamin.peterson | 2009-09-08 18:04:22 -0500 (Tue, 08 Sep 2009) | 1 line #6865 fix ref counting in initialization of pwd module ........ r74739 | georg.brandl | 2009-09-11 02:55:20 -0500 (Fri, 11 Sep 2009) | 1 line Move function back to its section. ........ ................
2009-09-11 19:36:27 -03:00
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("""
Merged revisions 74745 via svnmerge from svn+ssh://pythondev@svn.python.org/python/branches/py3k ................ r74745 | benjamin.peterson | 2009-09-11 17:24:02 -0500 (Fri, 11 Sep 2009) | 98 lines Merged revisions 74277,74321,74323,74326,74355,74465,74467,74488,74492,74513,74531,74549,74553,74625,74632,74643-74644,74647,74652,74666,74671,74727,74739 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r74277 | sean.reifschneider | 2009-08-01 18:54:55 -0500 (Sat, 01 Aug 2009) | 3 lines - Issue #6624: yArg_ParseTuple with "s" format when parsing argument with NUL: Bogus TypeError detail string. ........ r74321 | guilherme.polo | 2009-08-05 11:51:41 -0500 (Wed, 05 Aug 2009) | 1 line Easier reference to find (at least while svn continues being used). ........ r74323 | guilherme.polo | 2009-08-05 18:48:26 -0500 (Wed, 05 Aug 2009) | 1 line Typo. ........ r74326 | jesse.noller | 2009-08-05 21:05:56 -0500 (Wed, 05 Aug 2009) | 1 line Fix issue 4660: spurious task_done errors in multiprocessing, remove doc note for from_address ........ r74355 | gregory.p.smith | 2009-08-12 12:02:37 -0500 (Wed, 12 Aug 2009) | 2 lines comment typo fix ........ r74465 | vinay.sajip | 2009-08-15 18:23:12 -0500 (Sat, 15 Aug 2009) | 1 line Added section on logging to one file from multiple processes. ........ r74467 | vinay.sajip | 2009-08-15 18:34:47 -0500 (Sat, 15 Aug 2009) | 1 line Refined section on logging to one file from multiple processes. ........ r74488 | vinay.sajip | 2009-08-17 08:14:37 -0500 (Mon, 17 Aug 2009) | 1 line Further refined section on logging to one file from multiple processes. ........ r74492 | r.david.murray | 2009-08-17 14:26:49 -0500 (Mon, 17 Aug 2009) | 2 lines Issue 6685: 'toupper' -> 'upper' in cgi doc example explanation. ........ r74513 | skip.montanaro | 2009-08-18 09:37:52 -0500 (Tue, 18 Aug 2009) | 1 line missing module ref (issue6723) ........ r74531 | vinay.sajip | 2009-08-20 17:04:32 -0500 (Thu, 20 Aug 2009) | 1 line Added section on exceptions raised during logging. ........ r74549 | benjamin.peterson | 2009-08-24 12:42:36 -0500 (Mon, 24 Aug 2009) | 1 line fix pdf building by teaching latex the right encoding package ........ r74553 | r.david.murray | 2009-08-26 20:04:59 -0500 (Wed, 26 Aug 2009) | 2 lines Remove leftover text from end of sentence. ........ r74625 | benjamin.peterson | 2009-09-01 17:27:57 -0500 (Tue, 01 Sep 2009) | 1 line remove the check that classmethod's argument is a callable ........ r74632 | georg.brandl | 2009-09-03 02:27:26 -0500 (Thu, 03 Sep 2009) | 1 line #6828: fix wrongly highlighted blocks. ........ r74643 | georg.brandl | 2009-09-04 01:59:20 -0500 (Fri, 04 Sep 2009) | 2 lines Issue #2666: Handle BROWSER environment variable properly for unknown browser names in the webbrowser module. ........ r74644 | georg.brandl | 2009-09-04 02:55:14 -0500 (Fri, 04 Sep 2009) | 1 line #5047: remove Monterey support from configure. ........ r74647 | georg.brandl | 2009-09-04 03:17:04 -0500 (Fri, 04 Sep 2009) | 2 lines Issue #5275: In Cookie's Cookie.load(), properly handle non-string arguments as documented. ........ r74652 | georg.brandl | 2009-09-04 06:25:37 -0500 (Fri, 04 Sep 2009) | 1 line #6756: add some info about the "acct" parameter. ........ r74666 | georg.brandl | 2009-09-05 04:04:09 -0500 (Sat, 05 Sep 2009) | 1 line #6841: remove duplicated word. ........ r74671 | georg.brandl | 2009-09-05 11:47:17 -0500 (Sat, 05 Sep 2009) | 1 line #6843: add link from filterwarnings to where the meaning of the arguments is covered. ........ r74727 | benjamin.peterson | 2009-09-08 18:04:22 -0500 (Tue, 08 Sep 2009) | 1 line #6865 fix ref counting in initialization of pwd module ........ r74739 | georg.brandl | 2009-09-11 02:55:20 -0500 (Fri, 11 Sep 2009) | 1 line Move function back to its section. ........ ................
2009-09-11 19:36:27 -03:00
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
Merged revisions 74745 via svnmerge from svn+ssh://pythondev@svn.python.org/python/branches/py3k ................ r74745 | benjamin.peterson | 2009-09-11 17:24:02 -0500 (Fri, 11 Sep 2009) | 98 lines Merged revisions 74277,74321,74323,74326,74355,74465,74467,74488,74492,74513,74531,74549,74553,74625,74632,74643-74644,74647,74652,74666,74671,74727,74739 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r74277 | sean.reifschneider | 2009-08-01 18:54:55 -0500 (Sat, 01 Aug 2009) | 3 lines - Issue #6624: yArg_ParseTuple with "s" format when parsing argument with NUL: Bogus TypeError detail string. ........ r74321 | guilherme.polo | 2009-08-05 11:51:41 -0500 (Wed, 05 Aug 2009) | 1 line Easier reference to find (at least while svn continues being used). ........ r74323 | guilherme.polo | 2009-08-05 18:48:26 -0500 (Wed, 05 Aug 2009) | 1 line Typo. ........ r74326 | jesse.noller | 2009-08-05 21:05:56 -0500 (Wed, 05 Aug 2009) | 1 line Fix issue 4660: spurious task_done errors in multiprocessing, remove doc note for from_address ........ r74355 | gregory.p.smith | 2009-08-12 12:02:37 -0500 (Wed, 12 Aug 2009) | 2 lines comment typo fix ........ r74465 | vinay.sajip | 2009-08-15 18:23:12 -0500 (Sat, 15 Aug 2009) | 1 line Added section on logging to one file from multiple processes. ........ r74467 | vinay.sajip | 2009-08-15 18:34:47 -0500 (Sat, 15 Aug 2009) | 1 line Refined section on logging to one file from multiple processes. ........ r74488 | vinay.sajip | 2009-08-17 08:14:37 -0500 (Mon, 17 Aug 2009) | 1 line Further refined section on logging to one file from multiple processes. ........ r74492 | r.david.murray | 2009-08-17 14:26:49 -0500 (Mon, 17 Aug 2009) | 2 lines Issue 6685: 'toupper' -> 'upper' in cgi doc example explanation. ........ r74513 | skip.montanaro | 2009-08-18 09:37:52 -0500 (Tue, 18 Aug 2009) | 1 line missing module ref (issue6723) ........ r74531 | vinay.sajip | 2009-08-20 17:04:32 -0500 (Thu, 20 Aug 2009) | 1 line Added section on exceptions raised during logging. ........ r74549 | benjamin.peterson | 2009-08-24 12:42:36 -0500 (Mon, 24 Aug 2009) | 1 line fix pdf building by teaching latex the right encoding package ........ r74553 | r.david.murray | 2009-08-26 20:04:59 -0500 (Wed, 26 Aug 2009) | 2 lines Remove leftover text from end of sentence. ........ r74625 | benjamin.peterson | 2009-09-01 17:27:57 -0500 (Tue, 01 Sep 2009) | 1 line remove the check that classmethod's argument is a callable ........ r74632 | georg.brandl | 2009-09-03 02:27:26 -0500 (Thu, 03 Sep 2009) | 1 line #6828: fix wrongly highlighted blocks. ........ r74643 | georg.brandl | 2009-09-04 01:59:20 -0500 (Fri, 04 Sep 2009) | 2 lines Issue #2666: Handle BROWSER environment variable properly for unknown browser names in the webbrowser module. ........ r74644 | georg.brandl | 2009-09-04 02:55:14 -0500 (Fri, 04 Sep 2009) | 1 line #5047: remove Monterey support from configure. ........ r74647 | georg.brandl | 2009-09-04 03:17:04 -0500 (Fri, 04 Sep 2009) | 2 lines Issue #5275: In Cookie's Cookie.load(), properly handle non-string arguments as documented. ........ r74652 | georg.brandl | 2009-09-04 06:25:37 -0500 (Fri, 04 Sep 2009) | 1 line #6756: add some info about the "acct" parameter. ........ r74666 | georg.brandl | 2009-09-05 04:04:09 -0500 (Sat, 05 Sep 2009) | 1 line #6841: remove duplicated word. ........ r74671 | georg.brandl | 2009-09-05 11:47:17 -0500 (Sat, 05 Sep 2009) | 1 line #6843: add link from filterwarnings to where the meaning of the arguments is covered. ........ r74727 | benjamin.peterson | 2009-09-08 18:04:22 -0500 (Tue, 08 Sep 2009) | 1 line #6865 fix ref counting in initialization of pwd module ........ r74739 | georg.brandl | 2009-09-11 02:55:20 -0500 (Fri, 11 Sep 2009) | 1 line Move function back to its section. ........ ................
2009-09-11 19:36:27 -03:00
produces the following output:
.. code-block:: text
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
Merged revisions 70712,70714,70764-70765,70769-70771,70773,70776-70777,70788-70789,70824,70828,70832,70836,70842,70851,70855,70857,70866-70872,70883,70885,70893-70894,70896-70897,70903,70905-70907,70915,70927,70933,70951,70960,70962-70964,70998,71001,71006,71008,71010-71011,71019,71037,71056,71094,71101-71103,71106,71119,71123,71149-71150,71203,71212,71214-71217,71221,71240 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r70712 | benjamin.peterson | 2009-03-30 10:15:38 -0500 (Mon, 30 Mar 2009) | 1 line don't rely on the order dict repr #5605 ........ r70714 | brett.cannon | 2009-03-30 10:20:53 -0500 (Mon, 30 Mar 2009) | 1 line Add an entry to developers.txt. ........ r70764 | martin.v.loewis | 2009-03-30 17:06:33 -0500 (Mon, 30 Mar 2009) | 2 lines Add several VM developers. ........ r70765 | georg.brandl | 2009-03-30 17:09:34 -0500 (Mon, 30 Mar 2009) | 1 line #5199: make warning about vars() assignment more visible. ........ r70769 | andrew.kuchling | 2009-03-30 17:29:53 -0500 (Mon, 30 Mar 2009) | 1 line Remove comment ........ r70770 | andrew.kuchling | 2009-03-30 17:30:20 -0500 (Mon, 30 Mar 2009) | 1 line Add several items and placeholders ........ r70771 | andrew.kuchling | 2009-03-30 17:31:11 -0500 (Mon, 30 Mar 2009) | 1 line Many edits ........ r70773 | georg.brandl | 2009-03-30 17:43:00 -0500 (Mon, 30 Mar 2009) | 1 line #5039: make it clear that the impl. note refers to CPython. ........ r70776 | andrew.kuchling | 2009-03-30 18:08:24 -0500 (Mon, 30 Mar 2009) | 1 line typo fix ........ r70777 | andrew.kuchling | 2009-03-30 18:09:46 -0500 (Mon, 30 Mar 2009) | 1 line Add more items ........ r70788 | andrew.kuchling | 2009-03-30 20:21:01 -0500 (Mon, 30 Mar 2009) | 1 line Add various items ........ r70789 | georg.brandl | 2009-03-30 20:25:15 -0500 (Mon, 30 Mar 2009) | 1 line Fix a wrong struct field assignment (docstring as closure). ........ r70824 | georg.brandl | 2009-03-31 10:43:20 -0500 (Tue, 31 Mar 2009) | 1 line #5519: remove reference to Kodos, which seems dead. ........ r70828 | georg.brandl | 2009-03-31 10:50:16 -0500 (Tue, 31 Mar 2009) | 1 line #5581: fget argument of abstractproperty is optional as well. ........ r70832 | georg.brandl | 2009-03-31 11:31:11 -0500 (Tue, 31 Mar 2009) | 1 line #1386675: specify WindowsError as the exception, because it has a winerror attribute that EnvironmentError doesnt have. ........ r70836 | georg.brandl | 2009-03-31 11:50:25 -0500 (Tue, 31 Mar 2009) | 1 line #5417: replace references to undocumented functions by ones to documented functions. ........ r70842 | georg.brandl | 2009-03-31 12:13:06 -0500 (Tue, 31 Mar 2009) | 1 line #970783: document PyObject_Generic[GS]etAttr. ........ r70851 | georg.brandl | 2009-03-31 13:26:55 -0500 (Tue, 31 Mar 2009) | 1 line #837577: note cryptic return value of spawn*e on invalid env dicts. ........ r70855 | georg.brandl | 2009-03-31 13:30:37 -0500 (Tue, 31 Mar 2009) | 1 line #5245: note that PyRun_SimpleString doesnt return on SystemExit. ........ r70857 | georg.brandl | 2009-03-31 13:33:10 -0500 (Tue, 31 Mar 2009) | 1 line #5227: note that Py_Main doesnt return on SystemExit. ........ r70866 | georg.brandl | 2009-03-31 14:06:57 -0500 (Tue, 31 Mar 2009) | 1 line #4882: document named group behavior a bit better. ........ r70867 | georg.brandl | 2009-03-31 14:10:35 -0500 (Tue, 31 Mar 2009) | 1 line #1096310: document usage of sys.__std*__ a bit better. ........ r70868 | georg.brandl | 2009-03-31 14:12:17 -0500 (Tue, 31 Mar 2009) | 1 line #5190: export make_option in __all__. ........ r70869 | georg.brandl | 2009-03-31 14:14:42 -0500 (Tue, 31 Mar 2009) | 1 line Fix-up unwanted change. ........ r70870 | georg.brandl | 2009-03-31 14:26:24 -0500 (Tue, 31 Mar 2009) | 1 line #4411: document mro() and __mro__. (I hope I got it right.) ........ r70871 | georg.brandl | 2009-03-31 14:30:56 -0500 (Tue, 31 Mar 2009) | 1 line #5618: fix typo. ........ r70872 | r.david.murray | 2009-03-31 14:31:17 -0500 (Tue, 31 Mar 2009) | 3 lines Delete out-of-date and little-known README from the test directory by consensus of devs at pycon sprint. ........ r70883 | georg.brandl | 2009-03-31 15:41:08 -0500 (Tue, 31 Mar 2009) | 1 line #1674032: return value of flag from Event.wait(). OKed by Guido. ........ r70885 | tarek.ziade | 2009-03-31 15:48:31 -0500 (Tue, 31 Mar 2009) | 1 line using log.warn for sys.stderr ........ r70893 | georg.brandl | 2009-03-31 15:56:32 -0500 (Tue, 31 Mar 2009) | 1 line #1530012: move TQS section before raw strings. ........ r70894 | benjamin.peterson | 2009-03-31 16:06:30 -0500 (Tue, 31 Mar 2009) | 1 line take the usual lock precautions around _active_limbo_lock ........ r70896 | georg.brandl | 2009-03-31 16:15:33 -0500 (Tue, 31 Mar 2009) | 1 line #5598: document DocFileSuite *args argument. ........ r70897 | benjamin.peterson | 2009-03-31 16:34:42 -0500 (Tue, 31 Mar 2009) | 1 line fix Thread.ident when it is the main thread or a dummy thread #5632 ........ r70903 | georg.brandl | 2009-03-31 16:45:18 -0500 (Tue, 31 Mar 2009) | 1 line #1676135: remove trailing slashes from --prefix argument. ........ r70905 | georg.brandl | 2009-03-31 17:03:40 -0500 (Tue, 31 Mar 2009) | 1 line #5563: more documentation for bdist_msi. ........ r70906 | georg.brandl | 2009-03-31 17:11:53 -0500 (Tue, 31 Mar 2009) | 1 line #1651995: fix _convert_ref for non-ASCII characters. ........ r70907 | georg.brandl | 2009-03-31 17:18:19 -0500 (Tue, 31 Mar 2009) | 1 line #3427: document correct return type for urlopen().info(). ........ r70915 | georg.brandl | 2009-03-31 17:40:16 -0500 (Tue, 31 Mar 2009) | 1 line #5018: remove confusing paragraph. ........ r70927 | georg.brandl | 2009-03-31 18:01:27 -0500 (Tue, 31 Mar 2009) | 1 line Dont shout to users. ........ r70933 | georg.brandl | 2009-03-31 19:04:33 -0500 (Tue, 31 Mar 2009) | 2 lines Issue #5635: Fix running test_sys with tracing enabled. ........ r70951 | georg.brandl | 2009-04-01 09:02:27 -0500 (Wed, 01 Apr 2009) | 1 line Add Maksim, who worked on several issues at the sprint. ........ r70960 | jesse.noller | 2009-04-01 11:42:19 -0500 (Wed, 01 Apr 2009) | 1 line Issue 3270: document Listener address restrictions on windows ........ r70962 | brett.cannon | 2009-04-01 12:07:16 -0500 (Wed, 01 Apr 2009) | 2 lines Ron DuPlain was given commit privileges at PyCon 2009 to work on 3to2. ........ r70963 | georg.brandl | 2009-04-01 12:46:01 -0500 (Wed, 01 Apr 2009) | 1 line #5655: fix docstring oversight. ........ r70964 | brett.cannon | 2009-04-01 12:52:13 -0500 (Wed, 01 Apr 2009) | 2 lines Paul Kippes was given commit privileges to work on 3to2. ........ r70998 | georg.brandl | 2009-04-01 16:54:21 -0500 (Wed, 01 Apr 2009) | 1 line In Pdb, stop assigning values to __builtin__._ which interferes with the one commonly installed by gettext. ........ r71001 | brett.cannon | 2009-04-01 18:01:12 -0500 (Wed, 01 Apr 2009) | 3 lines Add my initials to Misc/developers.txt. Names are now sorted by number of characters in the person's name. ........ r71006 | georg.brandl | 2009-04-01 18:32:17 -0500 (Wed, 01 Apr 2009) | 1 line Cache the f_locals dict of the current frame, since every access to frame.f_locals overrides its contents with the real locals which undoes modifications made by the debugging user. ........ r71008 | andrew.kuchling | 2009-04-01 19:02:14 -0500 (Wed, 01 Apr 2009) | 1 line Typo fix ........ r71010 | benjamin.peterson | 2009-04-01 19:11:52 -0500 (Wed, 01 Apr 2009) | 1 line fix markup ........ r71011 | benjamin.peterson | 2009-04-01 19:12:47 -0500 (Wed, 01 Apr 2009) | 1 line this should be :noindex: ........ r71019 | georg.brandl | 2009-04-01 21:00:01 -0500 (Wed, 01 Apr 2009) | 1 line Fix test_doctest, missed two assignments to curframe. ........ r71037 | r.david.murray | 2009-04-01 23:34:04 -0500 (Wed, 01 Apr 2009) | 6 lines Clarify that datetime strftime does not produce leap seconds and datetime strptime does not accept it in the strftime behavior section of the datetime docs. Closes issue 2568. ........ r71056 | georg.brandl | 2009-04-02 12:43:07 -0500 (Thu, 02 Apr 2009) | 2 lines Actually the displayhook should print the repr. ........ r71094 | vinay.sajip | 2009-04-03 05:23:18 -0500 (Fri, 03 Apr 2009) | 1 line Added warning about logging use from asynchronous signal handlers. ........ r71101 | andrew.kuchling | 2009-04-03 16:43:00 -0500 (Fri, 03 Apr 2009) | 1 line Add some items ........ r71102 | andrew.kuchling | 2009-04-03 16:44:49 -0500 (Fri, 03 Apr 2009) | 1 line Fix 'the the'; grammar fix ........ r71103 | andrew.kuchling | 2009-04-03 16:45:29 -0500 (Fri, 03 Apr 2009) | 1 line Fix 'the the' duplication ........ r71106 | vinay.sajip | 2009-04-03 16:58:16 -0500 (Fri, 03 Apr 2009) | 1 line Clarified warning about logging use from asynchronous signal handlers. ........ r71119 | raymond.hettinger | 2009-04-04 00:37:47 -0500 (Sat, 04 Apr 2009) | 1 line Add helpful link. ........ r71123 | r.david.murray | 2009-04-04 01:39:56 -0500 (Sat, 04 Apr 2009) | 2 lines Fix error in description of 'oct' (issue 5678). ........ r71149 | georg.brandl | 2009-04-04 08:42:39 -0500 (Sat, 04 Apr 2009) | 1 line #5642: clarify map() compatibility to the builtin. ........ r71150 | georg.brandl | 2009-04-04 08:45:49 -0500 (Sat, 04 Apr 2009) | 1 line #5601: clarify that webbrowser is not meant for file names. ........ r71203 | benjamin.peterson | 2009-04-04 18:46:34 -0500 (Sat, 04 Apr 2009) | 1 line note how using iter* are unsafe while mutating and document iter(dict) ........ r71212 | georg.brandl | 2009-04-05 05:24:20 -0500 (Sun, 05 Apr 2009) | 1 line #1742837: expand HTTP server docs, and fix SocketServer ones to document methods as methods, not functions. ........ r71214 | georg.brandl | 2009-04-05 05:29:57 -0500 (Sun, 05 Apr 2009) | 1 line Normalize spelling of Mac OS X. ........ r71215 | georg.brandl | 2009-04-05 05:32:26 -0500 (Sun, 05 Apr 2009) | 1 line Avoid sure signs of a diseased mind. ........ r71216 | georg.brandl | 2009-04-05 05:41:02 -0500 (Sun, 05 Apr 2009) | 1 line #1718017: document the relation of os.path and the posixpath, ntpath etc. modules better. ........ r71217 | georg.brandl | 2009-04-05 05:48:47 -0500 (Sun, 05 Apr 2009) | 1 line #1726172: dont raise an unexpected IndexError if a voidresp() call has an empty response. ........ r71221 | vinay.sajip | 2009-04-05 06:06:24 -0500 (Sun, 05 Apr 2009) | 1 line Issue #5695: Moved logging.captureWarnings() call inside with statement in WarningsTest.test_warnings. ........ r71240 | georg.brandl | 2009-04-05 09:40:06 -0500 (Sun, 05 Apr 2009) | 1 line #5370: doc update about unpickling objects with custom __getattr__ etc. methods. ........
2009-04-05 16:13:16 -03:00
If we make the string literal a "raw" string, ``\n`` sequences are not converted
to newlines, but the backslash at the end of the line, and the newline character
in the source, are both included in the string as data. Thus, the example::
2007-08-15 11:28:22 -03:00
hello = r"This is a rather long string containing\n\
several lines of text much as you would do in C."
print(hello)
2007-08-15 11:28:22 -03:00
Merged revisions 74745 via svnmerge from svn+ssh://pythondev@svn.python.org/python/branches/py3k ................ r74745 | benjamin.peterson | 2009-09-11 17:24:02 -0500 (Fri, 11 Sep 2009) | 98 lines Merged revisions 74277,74321,74323,74326,74355,74465,74467,74488,74492,74513,74531,74549,74553,74625,74632,74643-74644,74647,74652,74666,74671,74727,74739 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r74277 | sean.reifschneider | 2009-08-01 18:54:55 -0500 (Sat, 01 Aug 2009) | 3 lines - Issue #6624: yArg_ParseTuple with "s" format when parsing argument with NUL: Bogus TypeError detail string. ........ r74321 | guilherme.polo | 2009-08-05 11:51:41 -0500 (Wed, 05 Aug 2009) | 1 line Easier reference to find (at least while svn continues being used). ........ r74323 | guilherme.polo | 2009-08-05 18:48:26 -0500 (Wed, 05 Aug 2009) | 1 line Typo. ........ r74326 | jesse.noller | 2009-08-05 21:05:56 -0500 (Wed, 05 Aug 2009) | 1 line Fix issue 4660: spurious task_done errors in multiprocessing, remove doc note for from_address ........ r74355 | gregory.p.smith | 2009-08-12 12:02:37 -0500 (Wed, 12 Aug 2009) | 2 lines comment typo fix ........ r74465 | vinay.sajip | 2009-08-15 18:23:12 -0500 (Sat, 15 Aug 2009) | 1 line Added section on logging to one file from multiple processes. ........ r74467 | vinay.sajip | 2009-08-15 18:34:47 -0500 (Sat, 15 Aug 2009) | 1 line Refined section on logging to one file from multiple processes. ........ r74488 | vinay.sajip | 2009-08-17 08:14:37 -0500 (Mon, 17 Aug 2009) | 1 line Further refined section on logging to one file from multiple processes. ........ r74492 | r.david.murray | 2009-08-17 14:26:49 -0500 (Mon, 17 Aug 2009) | 2 lines Issue 6685: 'toupper' -> 'upper' in cgi doc example explanation. ........ r74513 | skip.montanaro | 2009-08-18 09:37:52 -0500 (Tue, 18 Aug 2009) | 1 line missing module ref (issue6723) ........ r74531 | vinay.sajip | 2009-08-20 17:04:32 -0500 (Thu, 20 Aug 2009) | 1 line Added section on exceptions raised during logging. ........ r74549 | benjamin.peterson | 2009-08-24 12:42:36 -0500 (Mon, 24 Aug 2009) | 1 line fix pdf building by teaching latex the right encoding package ........ r74553 | r.david.murray | 2009-08-26 20:04:59 -0500 (Wed, 26 Aug 2009) | 2 lines Remove leftover text from end of sentence. ........ r74625 | benjamin.peterson | 2009-09-01 17:27:57 -0500 (Tue, 01 Sep 2009) | 1 line remove the check that classmethod's argument is a callable ........ r74632 | georg.brandl | 2009-09-03 02:27:26 -0500 (Thu, 03 Sep 2009) | 1 line #6828: fix wrongly highlighted blocks. ........ r74643 | georg.brandl | 2009-09-04 01:59:20 -0500 (Fri, 04 Sep 2009) | 2 lines Issue #2666: Handle BROWSER environment variable properly for unknown browser names in the webbrowser module. ........ r74644 | georg.brandl | 2009-09-04 02:55:14 -0500 (Fri, 04 Sep 2009) | 1 line #5047: remove Monterey support from configure. ........ r74647 | georg.brandl | 2009-09-04 03:17:04 -0500 (Fri, 04 Sep 2009) | 2 lines Issue #5275: In Cookie's Cookie.load(), properly handle non-string arguments as documented. ........ r74652 | georg.brandl | 2009-09-04 06:25:37 -0500 (Fri, 04 Sep 2009) | 1 line #6756: add some info about the "acct" parameter. ........ r74666 | georg.brandl | 2009-09-05 04:04:09 -0500 (Sat, 05 Sep 2009) | 1 line #6841: remove duplicated word. ........ r74671 | georg.brandl | 2009-09-05 11:47:17 -0500 (Sat, 05 Sep 2009) | 1 line #6843: add link from filterwarnings to where the meaning of the arguments is covered. ........ r74727 | benjamin.peterson | 2009-09-08 18:04:22 -0500 (Tue, 08 Sep 2009) | 1 line #6865 fix ref counting in initialization of pwd module ........ r74739 | georg.brandl | 2009-09-11 02:55:20 -0500 (Fri, 11 Sep 2009) | 1 line Move function back to its section. ........ ................
2009-09-11 19:36:27 -03:00
would print:
.. code-block:: text
2007-08-15 11:28:22 -03:00
This is a rather long string containing\n\
several lines of text much as you would do in C.
Strings can be concatenated (glued together) with the ``+`` operator, and
repeated with ``*``::
>>> word = 'Help' + 'A'
>>> word
'HelpA'
>>> '<' + word*5 + '>'
'<HelpAHelpAHelpAHelpAHelpA>'
Two string literals next to each other are automatically concatenated; the first
line above could also have been written ``word = 'Help' 'A'``; this only works
with two literals, not with arbitrary string expressions::
>>> 'str' 'ing' # <- This is ok
'string'
>>> 'str'.strip() + 'ing' # <- This is ok
'string'
>>> 'str'.strip() 'ing' # <- This is invalid
File "<stdin>", line 1, in ?
'str'.strip() 'ing'
^
SyntaxError: invalid syntax
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. As in the Icon programming language, substrings
can be specified with the *slice notation*: two indices separated by a colon.
::
2007-08-15 11:28:22 -03:00
>>> word[4]
'A'
>>> word[0:2]
'He'
>>> word[2:4]
'lp'
Slice indices have useful defaults; an omitted first index defaults to zero, an
omitted second index defaults to the size of the string being sliced. ::
>>> word[:2] # The first two characters
'He'
>>> word[2:] # Everything except the first two characters
'lpA'
2008-09-13 14:18:21 -03:00
Unlike a C string, Python strings cannot be changed. Assigning to an indexed
2007-08-15 11:28:22 -03:00
position in the string results in an error::
>>> word[0] = 'x'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'str' object does not support item assignment
2007-08-15 11:28:22 -03:00
>>> word[:1] = 'Splat'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'str' object does not support slice assignment
2007-08-15 11:28:22 -03:00
However, creating a new string with the combined content is easy and efficient::
>>> 'x' + word[1:]
'xelpA'
>>> 'Splat' + word[4]
'SplatA'
Here's a useful invariant of slice operations: ``s[:i] + s[i:]`` equals ``s``.
::
>>> word[:2] + word[2:]
'HelpA'
>>> word[:3] + word[3:]
'HelpA'
Degenerate slice indices are handled gracefully: an index that is too large is
replaced by the string size, an upper bound smaller than the lower bound returns
an empty string. ::
>>> word[1:100]
'elpA'
>>> word[10:]
''
>>> word[2:1]
''
Indices may be negative numbers, to start counting from the right. For example::
>>> word[-1] # The last character
'A'
>>> word[-2] # The last-but-one character
'p'
>>> word[-2:] # The last two characters
'pA'
>>> word[:-2] # Everything except the last two characters
'Hel'
But note that -0 is really the same as 0, so it does not count from the right!
::
>>> word[-0] # (since -0 equals 0)
'H'
Out-of-range negative slice indices are truncated, but don't try this for
single-element (non-slice) indices::
>>> word[-100:]
'HelpA'
>>> word[-10] # error
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: string index out of range
One way to remember how slices work is to think of the indices as pointing
*between* characters, with the left edge of the first character numbered 0.
Then the right edge of the last character of a string of *n* characters has
index *n*, for example::
2009-01-03 17:18:54 -04:00
+---+---+---+---+---+
2007-08-15 11:28:22 -03:00
| H | e | l | p | A |
2009-01-03 17:18:54 -04:00
+---+---+---+---+---+
0 1 2 3 4 5
2007-08-15 11:28:22 -03:00
-5 -4 -3 -2 -1
The first row of numbers gives the position of the indices 0...5 in the string;
the second row gives the corresponding negative indices. The slice from *i* to
*j* consists of all characters between the edges labeled *i* and *j*,
respectively.
For non-negative indices, the length of a slice is the difference of the
indices, if both are within bounds. For example, the length of ``word[1:3]`` is
2.
The built-in function :func:`len` returns the length of a string::
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
.. seealso::
:ref:`typesseq`
2009-01-03 17:18:54 -04:00
Strings are examples of *sequence types*, and support the common
operations supported by such types.
2007-08-15 11:28:22 -03:00
:ref:`string-methods`
Strings support a large number of methods for
2007-08-15 11:28:22 -03:00
basic transformations and searching.
:ref:`string-formatting`
Information about string formatting with :meth:`str.format` is described
here.
:ref:`old-string-formatting`
The old formatting operations invoked when strings and Unicode strings are
the left operand of the ``%`` operator are described in more detail here.
2007-08-15 11:28:22 -03:00
.. _tut-unicodestrings:
About Unicode
-------------
2007-08-15 11:28:22 -03:00
.. sectionauthor:: Marc-Andre Lemburg <mal@lemburg.com>
2008-09-13 14:18:21 -03:00
Starting with Python 3.0 all strings support Unicode (see
http://www.unicode.org/).
2007-08-15 11:28:22 -03:00
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
possible ordinals for script characters. Texts were typically bound to a code
page which mapped the ordinals to script characters. This lead to very much
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.
If you want to include special characters in a string,
2007-08-15 11:28:22 -03:00
you can do so by using the Python *Unicode-Escape* encoding. The following
example shows how::
>>> 'Hello\u0020World !'
'Hello World !'
2007-08-15 11:28:22 -03:00
The escape sequence ``\u0020`` indicates to insert the Unicode character with
the ordinal value 0x0020 (the space character) at the given position.
Other characters are interpreted by using their respective ordinal values
directly as Unicode ordinals. If you have literal strings in the standard
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.
Apart from these standard encodings, Python provides a whole set of other ways
of creating Unicode strings on the basis of a known encoding.
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
2007-08-15 11:28:22 -03:00
name of the encoding. Lowercase names for encodings are preferred. ::
2007-08-31 03:46:05 -03:00
>>> "Äpfel".encode('utf-8')
b'\xc3\x84pfel'
2007-08-15 11:28:22 -03:00
.. _tut-lists:
Lists
-----
Python knows a number of *compound* data types, used to group together other
values. The most versatile is the *list*, which can be written as a list of
comma-separated values (items) between square brackets. List items need not all
have the same type. ::
>>> a = ['spam', 'eggs', 100, 1234]
>>> a
['spam', 'eggs', 100, 1234]
Like string indices, list indices start at 0, and lists can be sliced,
concatenated and so on::
>>> a[0]
'spam'
>>> a[3]
1234
>>> a[-2]
100
>>> a[1:-1]
['eggs', 100]
>>> a[:2] + ['bacon', 2*2]
['spam', 'eggs', 'bacon', 4]
>>> 3*a[:3] + ['Boo!']
['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!']
Unlike strings, which are *immutable*, it is possible to change individual
elements of a list::
>>> a
['spam', 'eggs', 100, 1234]
>>> a[2] = a[2] + 23
>>> a
['spam', 'eggs', 123, 1234]
Assignment to slices is also possible, and this can even change the size of the
list or clear it entirely::
>>> # Replace some items:
... a[0:2] = [1, 12]
>>> a
[1, 12, 123, 1234]
>>> # Remove some:
... a[0:2] = []
>>> a
[123, 1234]
>>> # Insert some:
... a[1:1] = ['bletch', 'xyzzy']
>>> a
[123, 'bletch', 'xyzzy', 1234]
>>> # Insert (a copy of) itself at the beginning
>>> a[:0] = a
>>> a
[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
>>> # Clear the list: replace all items with an empty list
>>> a[:] = []
>>> a
[]
The built-in function :func:`len` also applies to lists::
Merged revisions 58886-58929 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r58892 | guido.van.rossum | 2007-11-06 15:32:56 -0800 (Tue, 06 Nov 2007) | 2 lines Add missing "return NULL" in overflow check in PyObject_Repr(). ........ r58893 | raymond.hettinger | 2007-11-06 17:13:09 -0800 (Tue, 06 Nov 2007) | 1 line Fix marshal's incorrect handling of subclasses of builtin types (backport candidate). ........ r58895 | raymond.hettinger | 2007-11-06 18:26:17 -0800 (Tue, 06 Nov 2007) | 1 line Optimize dict.fromkeys() with dict inputs. Useful for resetting bag/muliset counts for example. ........ r58896 | raymond.hettinger | 2007-11-06 18:45:46 -0800 (Tue, 06 Nov 2007) | 1 line Add build option for faster loop execution. ........ r58900 | nick.coghlan | 2007-11-07 03:57:51 -0800 (Wed, 07 Nov 2007) | 1 line Add missing NEWS entry ........ r58905 | christian.heimes | 2007-11-07 09:50:54 -0800 (Wed, 07 Nov 2007) | 1 line Backported fix for bug #1392 from py3k branch r58903. ........ r58906 | christian.heimes | 2007-11-07 10:30:22 -0800 (Wed, 07 Nov 2007) | 1 line Backport of Guido's review of my patch. ........ r58908 | raymond.hettinger | 2007-11-07 18:52:43 -0800 (Wed, 07 Nov 2007) | 1 line Add set.isdisjoint() ........ r58915 | raymond.hettinger | 2007-11-08 10:47:51 -0800 (Thu, 08 Nov 2007) | 1 line Reposition the decref (spotted by eagle-eye norwitz). ........ r58920 | georg.brandl | 2007-11-09 04:31:43 -0800 (Fri, 09 Nov 2007) | 2 lines Fix seealso link to sets docs. Do not merge to Py3k. ........ r58921 | georg.brandl | 2007-11-09 05:08:48 -0800 (Fri, 09 Nov 2007) | 2 lines Fix misleading example. ........ r58923 | georg.brandl | 2007-11-09 09:33:23 -0800 (Fri, 09 Nov 2007) | 3 lines Correct a comment about testing methods - nowadays most tests don't run directly on import. ........ r58924 | martin.v.loewis | 2007-11-09 14:56:30 -0800 (Fri, 09 Nov 2007) | 2 lines Add Amaury Forgeot d'Arc. ........ r58925 | raymond.hettinger | 2007-11-09 15:14:44 -0800 (Fri, 09 Nov 2007) | 1 line Optimize common case for dict.fromkeys(). ........ r58927 | raymond.hettinger | 2007-11-09 17:54:03 -0800 (Fri, 09 Nov 2007) | 1 line Use a freelist to speed-up block allocation and deallocation in collections.deque(). ........ r58929 | guido.van.rossum | 2007-11-10 14:12:24 -0800 (Sat, 10 Nov 2007) | 3 lines Issue 1416. Add getter, setter, deleter methods to properties that can be used as decorators to create fully-populated properties. ........
2007-11-10 19:39:45 -04:00
>>> a = ['a', 'b', 'c', 'd']
2007-08-15 11:28:22 -03:00
>>> len(a)
Merged revisions 58886-58929 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r58892 | guido.van.rossum | 2007-11-06 15:32:56 -0800 (Tue, 06 Nov 2007) | 2 lines Add missing "return NULL" in overflow check in PyObject_Repr(). ........ r58893 | raymond.hettinger | 2007-11-06 17:13:09 -0800 (Tue, 06 Nov 2007) | 1 line Fix marshal's incorrect handling of subclasses of builtin types (backport candidate). ........ r58895 | raymond.hettinger | 2007-11-06 18:26:17 -0800 (Tue, 06 Nov 2007) | 1 line Optimize dict.fromkeys() with dict inputs. Useful for resetting bag/muliset counts for example. ........ r58896 | raymond.hettinger | 2007-11-06 18:45:46 -0800 (Tue, 06 Nov 2007) | 1 line Add build option for faster loop execution. ........ r58900 | nick.coghlan | 2007-11-07 03:57:51 -0800 (Wed, 07 Nov 2007) | 1 line Add missing NEWS entry ........ r58905 | christian.heimes | 2007-11-07 09:50:54 -0800 (Wed, 07 Nov 2007) | 1 line Backported fix for bug #1392 from py3k branch r58903. ........ r58906 | christian.heimes | 2007-11-07 10:30:22 -0800 (Wed, 07 Nov 2007) | 1 line Backport of Guido's review of my patch. ........ r58908 | raymond.hettinger | 2007-11-07 18:52:43 -0800 (Wed, 07 Nov 2007) | 1 line Add set.isdisjoint() ........ r58915 | raymond.hettinger | 2007-11-08 10:47:51 -0800 (Thu, 08 Nov 2007) | 1 line Reposition the decref (spotted by eagle-eye norwitz). ........ r58920 | georg.brandl | 2007-11-09 04:31:43 -0800 (Fri, 09 Nov 2007) | 2 lines Fix seealso link to sets docs. Do not merge to Py3k. ........ r58921 | georg.brandl | 2007-11-09 05:08:48 -0800 (Fri, 09 Nov 2007) | 2 lines Fix misleading example. ........ r58923 | georg.brandl | 2007-11-09 09:33:23 -0800 (Fri, 09 Nov 2007) | 3 lines Correct a comment about testing methods - nowadays most tests don't run directly on import. ........ r58924 | martin.v.loewis | 2007-11-09 14:56:30 -0800 (Fri, 09 Nov 2007) | 2 lines Add Amaury Forgeot d'Arc. ........ r58925 | raymond.hettinger | 2007-11-09 15:14:44 -0800 (Fri, 09 Nov 2007) | 1 line Optimize common case for dict.fromkeys(). ........ r58927 | raymond.hettinger | 2007-11-09 17:54:03 -0800 (Fri, 09 Nov 2007) | 1 line Use a freelist to speed-up block allocation and deallocation in collections.deque(). ........ r58929 | guido.van.rossum | 2007-11-10 14:12:24 -0800 (Sat, 10 Nov 2007) | 3 lines Issue 1416. Add getter, setter, deleter methods to properties that can be used as decorators to create fully-populated properties. ........
2007-11-10 19:39:45 -04:00
4
2007-08-15 11:28:22 -03:00
It is possible to nest lists (create lists containing other lists), for
example::
>>> q = [2, 3]
>>> p = [1, q, 4]
>>> len(p)
3
>>> p[1]
[2, 3]
>>> p[1][0]
2
You can add something to the end of the list::
>>> p[1].append('xtra')
2007-08-15 11:28:22 -03:00
>>> p
[1, [2, 3, 'xtra'], 4]
>>> q
[2, 3, 'xtra']
Note that in the last example, ``p[1]`` and ``q`` really refer to the same
object! We'll come back to *object semantics* later.
.. _tut-firststeps:
First Steps Towards Programming
===============================
Of course, we can use Python for more complicated tasks than adding two and two
together. For instance, we can write an initial sub-sequence of the *Fibonacci*
series as follows::
>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
2008-01-07 13:32:13 -04:00
... print(b)
... a, b = b, a+b
2009-01-03 17:18:54 -04:00
...
2007-08-15 11:28:22 -03:00
1
1
2
3
5
8
This example introduces several new features.
* The first line contains a *multiple assignment*: the variables ``a`` and ``b``
simultaneously get the new values 0 and 1. On the last line this is used again,
demonstrating that the expressions on the right-hand side are all evaluated
first before any of the assignments take place. The right-hand side expressions
are evaluated from the left to the right.
* The :keyword:`while` loop executes as long as the condition (here: ``b < 10``)
remains true. In Python, like in C, any non-zero integer value is true; zero is
false. The condition may also be a string or list value, in fact any sequence;
anything with a non-zero length is true, empty sequences are false. The test
used in the example is a simple comparison. The standard comparison operators
are written the same as in C: ``<`` (less than), ``>`` (greater than), ``==``
(equal to), ``<=`` (less than or equal to), ``>=`` (greater than or equal to)
and ``!=`` (not equal to).
* The *body* of the loop is *indented*: indentation is Python's way of grouping
statements. Python does not (yet!) provide an intelligent input line editing
facility, so you have to type a tab or space(s) for each indented line. In
practice you will prepare more complicated input for Python with a text editor;
most text editors have an auto-indent facility. When a compound statement is
entered interactively, it must be followed by a blank line to indicate
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 :func:`print` function writes the value of the expression(s) it is
2007-08-15 11:28:22 -03:00
given. It differs from just writing the expression you want to write (as we did
2009-01-03 17:18:54 -04:00
earlier in the calculator examples) in the way it handles multiple
expressions, floating point quantities,
2007-08-15 11:28:22 -03:00
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)
2007-08-15 11:28:22 -03:00
The value of i is 65536
2008-08-05 06:04:16 -03:00
The keyword *end* can be used to avoid the newline after the output, or end
the output with a different string::
2007-08-15 11:28:22 -03:00
>>> a, b = 0, 1
>>> while b < 1000:
2008-08-05 06:04:16 -03:00
... print(b, end=' ')
2007-08-15 11:28:22 -03:00
... a, b = b, a+b
2009-01-03 17:18:54 -04:00
...
2007-08-15 11:28:22 -03:00
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987