Subsections


3. Python¼ò½é 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, "#", 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.

±¾ÊÖ²áÖеĺܶàʾÀý¶¼°üÀ¨×¢ÊÍ£¬ÉõÖÁÓÐһЩÔÚ½»»¥Ìáʾ·ûÖÐÕÛÐС£PythonÖеÄ×¢ÊÍÒÔ·ûºÅ "#" Æðʼ£¬Ò»Ö±µ½µ±Ç°ÐеĽáβ¡£×¢ÊÍ¿ÉÄܳöÏÖÔÚÒ»ÐеĿªÊ¼£¬Ò²¿ÉÄܸúÔÚ¿Õ¸ñ»ò³ÌÐò´úÂëÖ®ºó£¬µ«²»»á³öÏÖÔÚ×Ö·û´®ÖУ¬×Ö·û´®ÖÐµÄ "#" ºÅÖ»´ú±í "#" ºÅ¡£

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."


3.1 ½«Pythonµ±×÷¼ÆËãÆ÷ʹÓà 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.)

ÈÃÎÒÃÇÊÔÑéһЩ¼òµ¥µÄ Python ÃüÁî¡£Æô¶¯½âÊÍÆ÷È»ºóµÈ´ýÖ÷Ìáʾ·û">>"³öÏÖ£¨ÕâÓò»ÁËÌ«¾Ã£©¡£


3.1.1 ÊýÖµ 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:

½âÊÍÆ÷µÄÐÐΪ¾ÍÏñÊÇÒ»¸ö¼ÆËãÆ÷¡£Äã¿ÉÒÔÏòËüÊäÈëÒ»¸ö±í´ïʽ£¬Ëü»á·µ»Ø½á¹û¡£±í´ïʽµÄÓï·¨¼òÃ÷Ò׶®£º+£¬-£¬*£¬/ºÍ´ó¶àÊýÓïÑÔÖеÄÓ÷¨Ò»Ñù£¨±ÈÈçC»òPascal£©£¬À¨ºÅÓÃÓÚ·Ö×é¡£ÀýÈ磺

>>> 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
>>> # Integer division returns the floor:
... 7/3
2
>>> 7/-3
-3

Like in C, the equal sign ("=") is used to assign a value to a variable. The value of an assignment is not written:

ÏñcÒ»Ñù£¬µÈºÅ£¨"="£©ÓÃÓÚ¸ø±äÁ¿¸³Öµ¡£±»·ÖÅäµÄÖµÊÇÖ»¶ÁµÄ¡£

>>> 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

There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:

PythonÍêÈ«Ö§³Ö¸¡µãÊý£¬²»Í¬ÀàÐ͵IJÙ×÷Êý»ìÔÚÒ»Æðʱ£¬²Ù×÷·û»á°ÑÕûÐÍת»¯Îª¸¡µãÊý¡£

>>> 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.

Python ҲͬÑùÖ§³Ö¸´Êý£¬Ð鲿ÓÉÒ»¸öºó׺"j"»òÕß"J"À´±íʾ¡£´øÓзÇÁãʵ²¿µÄ¸´Êý¼ÇΪ"real+imagj)"£¬»òÕßÒ²¿ÉÒÔͨ¹ý"complex(real, img)"º¯Êý´´½¨¡£

>>> 1j * 1J
(-1+0j)
>>> 1j * complex(0,1)
(-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.

¸´Êý×ÜÊÇÓÉʵ²¿ºÍÐ鲿Á½²¿·Ö¸¡µãÊýÀ´±íʾ¡£¿ÉÒÔ´Ó z.real ºÍ z.imag µÃµ½¸´ÊýzµÄʵ²¿ºÍÐ鲿¡£

>>> a=1.5+0.5j
>>> a.real
1.5
>>> a.imag
0.5

The conversion functions to floating point and integer (float(), int() and long()) don't work for complex numbers -- there is no 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.

ÓÃÓÚÏò¸¡µãÊýºÍÕûÐÍת»¯µÄº¯Êý£¨float(), int() ºÍ long()£©²»ÄܶԸ´ÊýÆð×÷Óã­£­Ã»ÓÐʲô·½·¨¿ÉÒÔ½«¸´Êýת»¯ÎªÊµÊý¡£¿ÉÒÔʹÓÃabs(z)È¡µÃËüµÄÄ££¬Ò²¿ÉÒÔͨ¹ýz.realµÃµ½ËüµÄʵ²¿¡£

>>> 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:

½»»¥Ä£Ê½Ï£¬×î½üÒ»´Î±í´ïʽÊä³ö±£´æÔÚ _ ±äÁ¿ÖС£ÕâÒâζ×Å°Ñ Python µ±×ö×ÀÃæ¼ÆËãÆ÷ʹÓÃʱ£¬¿ÉÒÔ·½±ãµÄ½øÐÐÁ¬Ðø¼ÆË㣬ÀýÈ磺

>>> 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.

Õâ¸ö±äÁ¿¶ÔÓÚÓû§À´ËµÊÇÖ»¶ÁµÄ¡£²»ÒªÊÔͼȥ¸øËü¸³Öµ£­£­ÏÞÓÚ Python µÄÓï·¨¹æÔò£¬ÄãÖ»»á´´½¨Ò»¸öͬÃûµÄ¾Ö²¿±äÁ¿¸²¸ÇËü¡£


3.1.2 ×Ö·û´® 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:

³ýÁËÊýÖµ£¬ Python »¹¿ÉÒÔͨ¹ý¼¸ÖÖ²»Í¬µÄ·½·¨²Ù×÷×Ö·û´®¡£×Ö·û´®Óõ¥ÒýºÅ»òË«ÒýºÅ±êʶ£º

>>> '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.'

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

Note that newlines would still need to be embedded in the string using \n; the newline following the trailing backslash is discarded. This example would print the following:

×¢Òâ»»ÐÐÓà \n À´±íʾ£»·´Ð±¸ÜºóÃæµÄÐÂÐбêʶ£¨newline£¬Ëõд¡°n¡±£©»áת»»Îª»»Ðзû£¬Ê¾Àý»á°´Èçϸñʽ´òÓ¡£º

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.

If we make the string literal a ``raw'' string, however, the \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:

È»¶ø£¬Èç¹ûÎÒÃÇ´´½¨Ò»¸ö¡°ÐС±("raw")×Ö·û´®£¬\ nÐòÁоͲ»»áתΪ»»ÐУ¬Ô´ÂëÖеķ´Ð±¸ÜºÍ»»Ðзûn¶¼»á×öΪ×Ö·û´®ÖеÄÊý¾Ý´¦Àí¡£ÈçÏÂËùʾ£º

hello = r"This is a rather long string containing\n\
several lines of text much as you would do in C."

print hello

would print:

»á´òӡΪ£º

This is a rather long string containing\n\
several lines of text much as you would do in C.

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 """
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
"""

produces the following output:

Éú³ÉÒÔÏÂÊä³ö£º

Usage: thingy [OPTIONS]
     -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 print statement, described later, can be used to write strings without quotes or escapes.)

½âÊÍÆ÷´òÓ¡³öÀ´µÄ×Ö·û´®ÓëËüÃÇÊäÈëµÄÐÎʽÍêÈ«Ïàͬ£ºÄÚ²¿µÄÒýºÅ£¬Ó÷´Ð±¸Ü±êʶµÄÒýºÅºÍ¸÷ÖÖ¹Ö×Ö·û£¬¶¼¾«È·µÄÏÔʾ³öÀ´¡£Èç¹û×Ö·û´®Öаüº¬µ¥ÒýºÅ£¬²»°üº¬Ë«ÒýºÅ£¬¿ÉÒÔÓÃË«ÒýºÅÒýÓÃËü£¬·´Ö®¿ÉÒÔÓõ¥ÒýºÅ¡££¨ºóÃæ½éÉÜµÄ print Óï¾ä£¬¿ÉÒÔÔÚ²»Ê¹ÓÃÒýºÅºÍ·´Ð±¸ÜµÄÇé¿öÏÂÊä³ö×Ö·û´®£©¡£

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:

Á½¸ö×Ö·û´®ÖµÖ®¼ä»á×Ô¶¯Áª½Ó£¬ÉÏÀýµÚÒ»ÐпÉÒÔд³É¡°word = 'Help' 'A'¡±¡£ÕâÖÖ·½Ê½Ö»¶Ô×Ö·û´®ÖµÓÐЧ£¬ÈκÎ×Ö·û´®±í´ïʽ¶¼²»ÊÊÓÃÕâÖÖ·½·¨¡£

>>> '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. Like in Icon, substrings can be specified with the slice notation: two indices separated by a colon.

×Ö·û´®¿ÉÒÔÓÃϱ꣨Ë÷Òý£©²éѯ£»¾ÍÏñ C Ò»Ñù£¬×Ö·û´®µÄµÚÒ»¸ö×Ö·ûϱêÊÇ 0¡£ÕâÀïûÓжÀÁ¢µÄ×Ö·ûÀàÐÍ£¬×Ö·û½ö½öÊÇ´óСΪһµÄ×Ö·û´®¡£¾ÍÏñÔÚ Icon ÖÐÄÇÑù£¬×Ö·û´®µÄ×Ó´®¿ÉÒÔͨ¹ýÇÐƬ±êÖ¾À´±íʾ£ºÁ½¸öÓÉðºÅ¸ô¿ªµÄË÷Òý¡£

>>> 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.

ÇÐƬË÷Òý¿ÉÒÔʹÓÃĬÈÏÖµ£»Ç°Ò»¸öË÷ÒýĬÈÏֵΪ 0£¬ºóÒ»¸öË÷ÒýĬÈÏֵΪ±»ÇÐƬµÄ×Ö·û´®µÄ³¤¶È¡£

>>> word[:2]    # The first two characters
'He'
>>> word[2:]    # Everything except the first two characters
'lpA'

Unlike a C string, Python strings cannot be changed. Assigning to an indexed position in the string results in an error:

ºÍ C ×Ö·û´®²»Í¬£¬ Python ×Ö·û´®²»ÄܸÄд¡£°´×Ö·û´®Ë÷Òý¸³Öµ»á²úÉú´íÎó¡£

>>> word[0] = 'x'
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: 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

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.

ÇÐƬ²Ù×÷ÓÐÒ»¸öºÜÓÐÓõIJ»±äÐÔ£º

>>> 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!

²»¹ýÐèҪעÒâµÄÊÇ-0»¹ÊÇ0£¬ËüûÓдÓÓұ߼ÆÊý£¡

>>> 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

The best 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:

Àí½âÇÐƬµÄ×îºÃ·½Ê½ÊÇ°ÑË÷ÒýÊÓΪÁ½¸ö×Ö·ûÖ®¼äµÄµã£¬µÚÒ»¸ö×Ö·ûµÄ×ó±ßÊÇ0£¬×Ö·û´®ÖеÚn¸ö×Ö·ûµÄÓÒ±ßÊÇË÷Òýn£¬ÀýÈ磺

 +---+---+---+---+---+
 | H | e | l | p | A |
 +---+---+---+---+---+
 0   1   2   3   4   5
-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.

µÚÒ»ÐÐÊÇ×Ö·û´®Öиø¶¨µÄ0µ½5¸÷¸öË÷ÒýµÄλÖ㬵ڶþÐÐÊǶÔÓ¦µÄ¸ºË÷Òý¡£´Óiµ½jµÄÇÐƬÓÉÕâÁ½¸ö±êÖ¾Ö®¼äµÄ×Ö·û×é³É¡£

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.

¶ÔÓڷǸºË÷Òý£¬ÇÐƬ³¤¶È¾ÍÊÇÁ½Ë÷ÒýµÄ²î¡£ÀýÈ磬word[1:3]µÄ³¤¶ÈÊÇ2¡£

The built-in function len() returns the length of a string:

ÄÚÖú¯Êý len() ·µ»Ø×Ö·û´®³¤¶È£º

>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34

See Also:

Sequence Types
Strings, and the Unicode strings described in the next section, are examples of sequence types, and support the common operations supported by such types.
String Methods
Both strings and Unicode strings support a large number of methods for basic transformations and searching.
String Formatting Operations
The formatting operations invoked when strings and Unicode strings are the left operand of the % operator are described in more detail here.


3.1.3 Unicode ×Ö·û´® Unicode Strings

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.

´ÓPython2.0¿ªÊ¼£¬³ÌÐòÔ±ÃÇ¿ÉÒÔʹÓÃÒ»ÖÖеÄÊý¾ÝÀàÐÍÀ´´æ´¢Îı¾Êý¾Ý£ºUnicode ¶ÔÏó¡£Ëü¿ÉÒÔÓÃÓÚ´æ´¢¶àÖÖUnicodeÊý¾Ý£¨Çë²ÎÔÄ 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 possible ordinals for script characters and 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.

Unicode Õë¶ÔÏÖ´úºÍ¾ÉʽµÄÎı¾ÖÐËùÓеÄ×Ö·ûÌṩÁËÒ»¸öÐòÁС£ÒÔÇ°£¬×Ö·ûÖ»ÄÜʹÓÃ256¸öÐòºÅ£¬Îı¾Í¨³£Í¨¹ý°ó¶¨´úÂëÒ³À´Óë×Ö·ûÓ³Éä¡£ÕâºÜÈÝÒ×µ¼Ö»ìÂÒ£¬ÌرðÊÇÈí¼þµÄ¹ú¼Ê»¯£¨ internationalization £­£­Í¨³£Ð´×ö¡°i18n¡±£­£­¡°i¡±+ "i" +¡°n¡±£©¡£ Unicode ͨ¹ýΪËùÓÐ×Ö·û¶¨ÒåÒ»¸öͳһµÄ´úÂëÒ³½â¾öÁËÕâ¸öÎÊÌâ¡£

Creating Unicode strings in Python is just as simple as creating normal strings:

Python Öж¨ÒåÒ»¸ö Unicode ×Ö·û´®ºÍ¶¨ÒåÒ»¸öÆÕͨ×Ö·û´®Ò»Ñù¼òµ¥£º

>>> u'Hello World !'
u'Hello World !'

The small "u" in front of the quote indicates that an Unicode string is supposed to be created. If you want to include special characters in the string, you can do so by using the Python Unicode-Escape encoding. The following example shows how:

ÒýºÅǰСдµÄ¡°u¡±±íʾÕâÀï´´½¨µÄÊÇÒ»¸ö Unicode ×Ö·û´®¡£Èç¹ûÄãÏë¼ÓÈëÒ»¸öÌØÊâ×Ö·û£¬¿ÉÒÔʹÓà Python µÄ Unicode-Escape ±àÂë¡£ÈçÏÂÀýËùʾ£º

>>> u'Hello\u0020World !'
u'Hello World !'

The escape sequence \u0020 indicates to insert the Unicode character with the ordinal value 0x0020 (the space character) at the given position.

±»Ìæ»»µÄ \u0020 ±êʶ±íʾÔÚ¸ø¶¨Î»ÖòåÈë±àÂëֵΪ 0x0020 µÄ Unicode ×Ö·û£¨¿Õ¸ñ·û£©¡£

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.

ÆäËü×Ö·ûÒ²»á±»Ö±½Ó½âÊͳɶÔÓ¦µÄ Unicode Âë¡£Èç¹ûÄãÓÐÒ»¸öÔÚÎ÷·½¹ú¼Ò³£ÓÃµÄ Latin-1 ±àÂë×Ö·û´®£¬Äã¿ÉÒÔ·¢ÏÖ Unicode ×Ö·û¼¯µÄÇ°256¸ö×Ö·ûÓë 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'.

ÁíÍ⣬ÓÐÒ»ÖÖÓëÆÕͨ×Ö·û´®ÏàͬµÄÐÐģʽ¡£ÒªÊ¹Óà Python µÄ Raw-Unicode-Escape ±àÂ룬ÄãÐèÒªÔÚ×Ö·û´®µÄÒýºÅÇ°¼ÓÉÏ ur ǰ׺¡£Èç¹ûÔÚСд¡°u¡±Ç°Óв»Ö¹Ò»¸ö·´Ð±¸Ü£¬ËüÖ»»á°ÑÄÇЩµ¥¶ÀµÄ
uXXXX ת»¯ÎªUnicode×Ö·û¡£

>>> 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.

×÷ΪÕâЩ±àÂë±ê×¼µÄÒ»²¿·Ö£¬ Python ÌṩÁËÒ»¸öÍ걸µÄ·½·¨¼¯ÓÃÓÚ´ÓÒÑÖªµÄ±àÂ뼯´´½¨ Unicode ×Ö·û´®¡£

The built-in function 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 str(), conversion takes place using this default encoding.

ÄÚÖú¯Êý unicode() ÌṩÁË·ÃÎÊ£¨±àÂëºÍ½âÂ룩ËùÓÐÒÑ×¢²áµÄ Unicode ±àÂëµÄ·½·¨¡£ËüÄÜת»»ÖÚËùÖÜÖªµÄ Latin-1, ASCII, UTF-8, ºÍ UTF-16¡£ºóÃæµÄÁ½¸ö¿É±ä³¤±àÂë×Ö·û¼¯ÓÃÒ»¸ö»ò¶à¸ö byte ´æ´¢ Unicode ×Ö·û¡£Ä¬ÈϵÄ×Ö·û¼¯ÊÇ ASCII£¬ËüÖ»´¦Àí0µ½127µÄ±àÂ룬¾Ü¾øÆäËüµÄ×Ö·û²¢·µ»ØÒ»¸ö´íÎó¡£µ±Ò»¸ö Unicode ×Ö·û´®±»´òÓ¡¡¢Ð´ÈëÎļþ»òͨ¹ý str() ת»¯Ê±£¬ËüÃDZ»Ì滻ΪĬÈϵıàÂë¡£

>>> 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 encode() method that takes one argument, the name of the encoding. Lowercase names for encodings are preferred.

Òª°ÑÒ»¸ö Unicode ×Ö·û´®ÓÃÖ¸¶¨µÄ×Ö·û¼¯×ª»¯³É8λ×Ö·û´®£¬¿ÉÒÔʹÓà Unicode ¶ÔÏóÌṩµÄ encode() ·½·¨£¬ËüÓÐÒ»¸ö²ÎÊýÓÃÒÔÖ¸¶¨±àÂëÃû³Æ¡£±àÂëÃû³ÆСд¡£

>>> 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 unicode() function with the encoding name as the second argument.

Èç¹ûÄãÓÐÒ»¸öÌض¨±àÂëµÄ×Ö·û´®£¬ÏëÒª°ÑËüתΪ Unicode ×Ö·û¼¯£¬£¬¿ÉÒÔʹÓà encode() º¯Êý£¬ËüÒÔ±àÂëÃû×öΪµÚ¶þ¸ö²ÎÊý¡£

>>> unicode('\xc3\xa4\xc3\xb6\xc3\xbc', 'utf-8')
u'\xe4\xf6\xfc'


3.1.4 Á´±í 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.

Python ÒѾ­ÓÐÁ˼¸¸ö¸´ºÏÊý¾ÝÀàÐÍ£¬ÓÃÓÚ×éÖ¯ÆäËüµÄÖµ¡£×îͨÓõÄÊÇÁ´±í£¬ËüдΪÖÐÀ¨Ö®¼äÓöººÅ·Ö¸ôµÄÒ»ÁÐÖµ£¨×ÓÏ£¬Á´±íµÄ×ÓÏî²»Ò»¶¨ÊÇͬһÀàÐ͵ÄÖµ¡£

>>> 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] + ['Boe!']
['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!']

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:

¿ÉÒÔ½øÐÐÇÐƬ²Ù×÷£¬ÉõÖÁ»¹¿ÉÒԸıäÁ´±íµÄ´óС£º

>>> # 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]
>>> a[:0] = a     # Insert (a copy of) itself at the beginning
>>> a
[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]

The built-in function len() also applies to lists:

ÄÚÖú¯Êýlen()ҲͬÑù¿ÉÒÔÓÃÓÚÁ´±í£º

>>> len(a)
8

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
>>> p[1].append('xtra')     # See section 5.1
>>> 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.

×¢Òâ×îºóÒ»¸öÀý×Ó£¬ p[1] ºÍ q ʵ¼ÊÉÏÖ¸Ïòͬһ¸ö¶ÔÏó£¡ÎÒÃÇÔÚºóÃæ»á½²µ½¶ÔÏóÓï·¨¡£


3.2 ¿ªÊ¼±à³Ì 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:

µ±È»£¬ÎÒÃÇ¿ÉÒÔÓà Python ×ö±È2¼Ó2¸ü¸´ÔÓµÄÊ¡£ÀýÈ磬ÎÒÃÇ¿ÉÒÔÓÃÒÔϵķ½·¨Êä³ö·Æ²¨ÄÇÆõ£¨Fibonacci£©ÐòÁеÄ×ÓÐòÁУº

>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
...       print b
...       a, b = b, a+b
...
1
1
2
3
5
8

This example introduces several new features.

ʾÀýÖнéÉÜÁËһЩй¦ÄÜ£º

ÒëÕߣºÁõöÎ(march.liu AT gmail DOT com) ÓÉ£ºlimodouת(limodou AT gmail DOT com)
See About this document... for information on suggesting changes.