cinap_lenrekadd hg and python4bb9e2215 years agoHistory
2279 lines · 103.7 KB · Text
RawDownload
                          Python 2.3 Quick Reference   25 Jan 2003  upgraded by Raymond Hettinger for Python 2.3 16 May 2001  upgraded by Richard Gruet and Simon Brunning for Python 2.0 2000/07/18  upgraded by Richard Gruet, rgruet@intraware.com for Python 1.5.2from V1.3 ref1995/10/30, by Chris Hoffmann, choffman@vicorp.com Based on:    Python Bestiary, Author: Ken Manheimer, ken.manheimer@nist.gov    Python manuals, Authors: Guido van Rossum and Fred Drake    What's new in Python 2.0, Authors: A.M. Kuchling and Moshe Zadka    python-mode.el, Author: Tim Peters, tim_one@email.msn.com     and the readers of comp.lang.python Python's nest: http://www.python.org     Developement: http://python.sourceforge.net/    ActivePython : http://www.ActiveState.com/ASPN/Python/newsgroup: comp.lang.python  Help desk: help@python.orgResources: http://starship.python.net/           http://www.vex.net/parnassus/           http://aspn.activestate.com/ASPN/Cookbook/PythonFAQ:       http://www.python.org/cgi-bin/faqw.pyFull documentation: http://www.python.org/doc/Excellent reference books:           Python Essential Reference by David Beazley (New Riders)           Python Pocket Reference by Mark Lutz (O'Reilly)  Invocation Options python [-diOStuUvxX?] [-c command | script | - ] [args]                               Invocation OptionsOption                                  Effect-c cmd  program passed in as string (terminates option list)-d      Outputs parser debugging information (also PYTHONDEBUG=x)-E      ignore environment variables (such as PYTHONPATH)-h      print this help message and exit-i      Inspect interactively after running script (also PYTHONINSPECT=x) and        force prompts, even if stdin appears not to be a terminal-O      optimize generated bytecode (a tad; also PYTHONOPTIMIZE=x)-OO     remove doc-strings in addition to the -O optimizations-Q arg  division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew-S      Don't perform 'import site' on initialization-t      Issue warnings about inconsistent tab usage (-tt: issue errors)-u      Unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x).-v      Verbose (trace import statements) (also PYTHONVERBOSE=x)-W arg : warning control (arg is action:message:category:module:lineno)-x      Skip first line of source, allowing use of non-unix Forms of #!cmd-?      Help!-c      Specify the command to execute (see next section). This terminates thecommand option list (following options are passed as arguments to the command).        the name of a python file (.py) to execute read from stdin.script  Anything afterward is passed as options to python script or command,        not interpreted as an option to interpreter itself.args    passed to script or command (in sys.argv[1:])        If no script or command, Python enters interactive mode.   * Available IDEs in std distrib: IDLE (tkinter based, portable), Pythonwin    (Windows).   Environment variables                              Environment variables    Variable                                 EffectPYTHONHOME       Alternate prefix directory (or prefix;exec_prefix). The                 default module search path uses prefix/lib                 Augments the default search path for module files. The format                 is the same as the shell's $PATH: one or more directory                 pathnames separated by ':' or ';' without spaces around                 (semi-)colons!PYTHONPATH       On Windows first search for Registry key HKEY_LOCAL_MACHINE\                 Software\Python\PythonCore\x.y\PythonPath (default value). You                 may also define a key named after your application with a                 default string value giving the root directory path of your                 app.                 If this is the name of a readable file, the Python commands inPYTHONSTARTUP    that file are executed before the first prompt is displayed in                 interactive mode (no default).PYTHONDEBUG      If non-empty, same as -d optionPYTHONINSPECT    If non-empty, same as -i optionPYTHONSUPPRESS   If non-empty, same as -s optionPYTHONUNBUFFERED If non-empty, same as -u optionPYTHONVERBOSE    If non-empty, same as -v optionPYTHONCASEOK     If non-empty, ignore case in file/module names (imports)    Notable lexical entities Keywords     and       del       for       is        raise    assert    elif      from      lambda    return    break     else      global    not       try    class     except    if        or        while    continue  exec      import    pass      yield    def       finally   in        print   * (list of keywords in std module: keyword)  * Illegitimate Tokens (only valid in strings): @ $ ?  * A statement must all be on a single line. To break a statement over    multiple lines use "\", as with the C preprocessor.    Exception: can always break when inside any (), [], or {} pair, or in    triple-quoted strings.  * More than one statement can appear on a line if they are separated with    semicolons (";").  * Comments start with "#" and continue to end of line. Identifiers         (letter | "_")  (letter | digit | "_")*   * Python identifiers keywords, attributes, etc. are case-sensitive.  * Special forms: _ident (not imported by 'from module import *'); __ident__    (system defined name);               __ident (class-private name mangling) Strings     "a string enclosed by double quotes"    'another string delimited by single quotes and with a " inside'    '''a string containing embedded newlines and quote (') marks, can be    delimited with triple quotes.'''    """ may also use 3- double quotes as delimiters """    u'a unicode string'   U"Another unicode string"    r'a raw string where \ are kept (literalized): handy for regular    expressions and windows paths!'    R"another raw string"    -- raw strings cannot end with a \    ur'a unicode raw string'   UR"another raw unicode"         Use \ at end of line to continue a string on next line.        adjacent strings are concatened, e.g. 'Monty' ' Python' is the same as        'Monty Python'.        u'hello' + ' world'  --> u'hello world'   (coerced to unicode)     String Literal Escapes      \newline  Ignored (escape newline)     \\ Backslash (\)        \e Escape (ESC)        \v Vertical Tab (VT)     \' Single quote (')     \f Formfeed (FF)       \OOO char with octal value OOO     \" Double quote (")     \n Linefeed (LF)     \a Bell (BEL)           \r Carriage Return (CR) \xHH  char with hex value HH     \b Backspace (BS)       \t Horizontal Tab (TAB)     \uHHHH  unicode char with hex value HHHH, can only be used in unicode string     \UHHHHHHHH  unicode char with hex value HHHHHHHH, can only be used in unicode string     \AnyOtherChar is left as-is   * NUL byte (\000) is NOT an end-of-string marker; NULs may be embedded in    strings.  * Strings (and tuples) are immutable: they cannot be modified. Numbers     Decimal integer: 1234, 1234567890546378940L        (or l)    Octal integer: 0177, 0177777777777777777 (begin with a 0)    Hex integer: 0xFF, 0XFFFFffffFFFFFFFFFF (begin with 0x or 0X)    Long integer (unlimited precision): 1234567890123456    Float (double precision): 3.14e-10, .001, 10., 1E3    Complex: 1J, 2+3J, 4+5j (ends with J or j, + separates (float) real and    imaginary parts) Sequences   * String of length 0, 1, 2 (see above)    '', '1', "12", 'hello\n'  * Tuple of length 0, 1, 2, etc:    () (1,) (1,2)     # parentheses are optional if len > 0  * List of length 0, 1, 2, etc:    [] [1] [1,2] Indexing is 0-based. Negative indices (usually) mean count backwards from endof sequence. Sequence slicing [starting-at-index : but-less-than-index]. Start defaults to'0'; End defaults to 'sequence-length'. a = (0,1,2,3,4,5,6,7)    a[3] ==> 3    a[-1] ==> 7    a[2:4] ==> (2, 3)    a[1:] ==> (1, 2, 3, 4, 5, 6, 7)    a[:3] ==> (0, 1, 2)    a[:] ==> (0,1,2,3,4,5,6,7)  # makes a copy of the sequence. Dictionaries (Mappings)     {}                              # Zero length empty dictionary    {1 : 'first'}                   # Dictionary with one (key, value) pair    {1 : 'first',  'next': 'second'}    dict([('one',1),('two',2)])     # Construct a dict from an item list    dict('one'=1, 'two'=2)          # Construct a dict using keyword args    dict.fromkeys(['one', 'keys'])  # Construct a dict from a sequence Operators and their evaluation order                      Operators and their evaluation orderHighest             Operator                             Comment        (...) [...] {...} `...`           Tuple, list & dict. creation; string                                          conv.        s[i]  s[i:j]  s.attr f(...)       indexing & slicing; attributes, fct                                          calls        +x, -x, ~x                        Unary operators        x**y                              Power        x*y  x/y  x%y x//y                mult, division, modulo, floor division        x+y  x-y                          addition, subtraction        x<<y   x>>y                       Bit shifting        x&y                               Bitwise and        x^y                               Bitwise exclusive or        x|y                               Bitwise or        x<y  x<=y  x>y  x>=y  x==y x!=y   Comparison,        x<>y                              identity,        x is y   x is not y               membership        x in s   x not in s        not x                             boolean negation        x and y                           boolean and        x or y                            boolean orLowest  lambda args: expr                 anonymous function Alternate names are defined in module operator (e.g. __add__ and add for +)Most operators are overridable. Many binary operators also support augmented assignment:        x += 1                            # Same as x = x + 1  Basic Types and Their Operations Comparisons (defined between *any* types)                ComparisonsComparison         Meaning          Notes<          strictly less than        (1)<=         less than or equal to>          strictly greater than>=         greater than or equal to==         equal to!= or <>   not equal tois         object identity           (2)is not     negated object identity   (2) Notes :    Comparison behavior can be overridden for a given class by defining specialmethod __cmp__.    The above comparisons return True or False which are of type bool(a subclass of int) and behave exactly as 1 or 0 except for their type andthat they print as True or False instead of 1 or 0.    (1) X < Y < Z < W has expected meaning, unlike C    (2) Compare object identities (i.e. id(object)), not object values. Boolean values and operators                          Boolean values and operators              Value or Operator                         Returns           NotesNone, numeric zeros, empty sequences and      Falsemappingsall other values                              Truenot x                                         True if x is False, else                                              Truex or y                                        if x is False then y, else   (1)                                              xx and y                                       if x is False then x, else   (1)                                              y Notes :    Truth testing behavior can be overridden for a given class by definingspecial method __nonzero__.    (1) Evaluate second arg only if necessary to determine outcome. None     None is used as default return value on functions. Built-in single object    with type NoneType.    Input that evaluates to None does not print when running Python    interactively. Numeric types Floats, integers and long integers.     Floats are implemented with C doubles.    Integers are implemented with C longs.    Long integers have unlimited size (only limit is system resources) Operators on all numeric types            Operators on all numeric types Operation                    Resultabs(x)       the absolute value of xint(x)       x converted to integerlong(x)      x converted to long integerfloat(x)     x converted to floating point-x           x negated+x           x unchangedx + y        the sum of x and yx - y        difference of x and yx * y        product of x and yx / y        quotient of x and yx % y        remainder of x / ydivmod(x, y) the tuple (x/y, x%y)x ** y       x to the power y (the same as pow(x, y)) Bit operators on integers and long integers               Bit operatorsOperation             >Result~x        the bits of x invertedx ^ y     bitwise exclusive or of x and yx & y     bitwise and of x and yx | y     bitwise or of x and yx << n    x shifted left by n bitsx >> n    x shifted right by n bits Complex Numbers   * represented as a pair of machine-level double precision floating point    numbers.  * The real and imaginary value of a complex number z can be retrieved through    the attributes z.real and z.imag. Numeric exceptions TypeError    raised on application of arithmetic operation to non-numberOverflowError     numeric bounds exceededZeroDivisionError     raised when zero second argument of div or modulo opFloatingPointError     raised when a floating point operation fails Operations on all sequence types (lists, tuples, strings)                 Operations on all sequence typesOperation                     Result                     Notesx in s     True if an item of s is equal to x, else Falsex not in s False if an item of s is equal to x, else Truefor x in s: loops over the sequences + t      the concatenation of s and ts * n, n*s n copies of s concatenateds[i]       i'th item of s, origin 0                       (1)s[i:j]     slice of s from i (included) to j (excluded) (1), (2)len(s)     length of smin(s)     smallest item of smax(s)     largest item of (s)iter(s)    returns an iterator over s.  iterators define __iter__ and next() Notes :    (1) if i or j is negative, the index is relative to the end of the string,ie len(s)+ i or len(s)+j is         substituted. But note that -0 is still 0.    (2) The slice of s from i to j is defined as the sequence of items withindex k such that i <= k < j.          If i or j is greater than len(s), use len(s). If i is omitted, uselen(s). If i is greater than or          equal to j, the slice is empty. Operations on mutable (=modifiable) sequences (lists)                  Operations on mutable sequences   Operation                      Result                   Notess[i] =x          item i of s is replaced by xs[i:j] = t       slice of s from i to j is replaced by tdel s[i:j]       same as s[i:j] = []s.append(x)      same as s[len(s) : len(s)] = [x]s.count(x)       return number of i's for which s[i] == xs.extend(x)      same as s[len(s):len(s)]= xs.index(x)       return smallest i such that s[i] == x      (1)s.insert(i, x)   same as s[i:i] = [x] if i >= 0s.pop([i])       same as x = s[i]; del s[i]; return x       (4)s.remove(x)      same as del s[s.index(x)]                  (1)s.reverse()      reverse the items of s in place            (3)s.sort([cmpFct]) sort the items of s in place             (2), (3) Notes :    (1) raise a ValueError exception when x is not found in s (i.e. out ofrange).     (2) The sort() method takes an optional argument specifying a comparisonfct of 2 arguments (list items) which should          return -1, 0, or 1 depending on whether the 1st argument isconsidered smaller than, equal to, or larger than the 2nd          argument. Note that this slows the sorting process down considerably.     (3) The sort() and reverse() methods modify the list in place for economyof space when sorting or reversing a large list.           They don't return the sorted or reversed list to remind you of thisside effect.     (4) [New 1.5.2] The optional  argument i defaults to -1, so that by default the lastitem is removed and returned.   Operations on mappings (dictionaries)                          Operations on mappings        Operation                          Result                  Noteslen(d)                     the number of items in dd[k]                       the item of d with key k                 (1)d[k] = x                   set d[k] to xdel d[k]                   remove d[k] from d                       (1)d.clear()                  remove all items from dd.copy()                   a shallow copy of dd.get(k,defaultval)        the item of d with key k                 (4)d.has_key(k)               True if d has key k, else Falsed.items()                  a copy of d's list of (key, item) pairs  (2)d.iteritems()              an iterator over (key, value) pairs      (7)d.iterkeys()               an iterator over the keys of d           (7)d.itervalues()             an iterator over the values of d         (7)d.keys()                   a copy of d's list of keys               (2)d1.update(d2)              for k, v in d2.items(): d1[k] = v        (3)d.values()                 a copy of d's list of values             (2)d.pop(k)                   remove d[k] and return its valued.popitem()                remove and return an arbitrary           (6)                           (key, item) paird.setdefault(k,defaultval) the item of d with key k                 (5)     Notes :      TypeError is raised if key is not acceptable      (1) KeyError is raised if key k is not in the map      (2) Keys and values are listed in random order      (3) d2 must be of the same type as d1      (4) Never raises an exception if k is not in the map, instead it returns    defaultVal.          defaultVal is optional, when not provided and k is not in the map,    None is returned.      (5) Never raises an exception if k is not in the map, instead it returns    defaultVal, and adds k to map with value defaultVal. defaultVal is    optional. When not provided and k is not in the map, None is returned and    added to map.      (6) Raises a KeyError if the dictionary is emtpy.      (7) While iterating over a dictionary, the values may be updated but          the keys cannot be changed. Operations on strings Note that these string methods largely (but not completely) supersede thefunctions available in the string module.                               Operations on strings    Operation                             Result                          Notess.capitalize()    return a copy of s with only its first character                  capitalized.s.center(width)   return a copy of s centered in a string of length width  (1)                  .s.count(sub[      return the number of occurrences of substring sub in     (2),start[,end]])    string s.s.decode(([       return a decoded version of s.                           (3)  encoding  [,errors]])s.encode([        return an encoded version of s. Default encoding is the  encoding        current default string encoding.                         (3)  [,errors]])s.endswith(suffix return true if s ends with the specified suffix,         (2)  [,start[,end]]) otherwise return False.s.expandtabs([    return a copy of s where all tab characters are          (4)tabsize])         expanded using spaces.s.find(sub[,start return the lowest index in s where substring sub is      (2)[,end]])          found. Return -1 if sub is not found.s.index(sub[      like find(), but raise ValueError when the substring is  (2),start[,end]])    not found.s.isalnum()       return True if all characters in s are alphanumeric,     (5)                  False otherwise.s.isalpha()       return True if all characters in s are alphabetic,       (5)                  False otherwise.s.isdigit()       return True if all characters in s are digit             (5)                  characters, False otherwise.s.islower()       return True if all characters in s are lowercase, False  (6)                  otherwise.s.isspace()       return True if all characters in s are whitespace        (5)                  characters, False otherwise.s.istitle()       return True if string s is a titlecased string, False    (7)                  otherwise.s.isupper()       return True if all characters in s are uppercase, False  (6)                  otherwise.s.join(seq)       return a concatenation of the strings in the sequence                  seq, seperated by 's's.s.ljust(width)    return s left justified in a string of length width.    (1),                                                                           (8)s.lower()         return a copy of s converted to lowercase.s.lstrip()        return a copy of s with leading whitespace removed.s.replace(old,    return a copy of s with all occurrences of substring     (9)new[, maxsplit])  old replaced by new.s.rfind(sub[      return the highest index in s where substring sub is     (2),start[,end]])    found. Return -1 if sub is not found.s.rindex(sub[     like rfind(), but raise ValueError when the substring    (2),start[,end]])    is not found.s.rjust(width)    return s right justified in a string of length width.   (1),                                                                           (8)s.rstrip()        return a copy of s with trailing whitespace removed.s.split([sep[     return a list of the words in s, using sep as the       (10),maxsplit]])      delimiter string.s.splitlines([    return a list of the lines in s, breaking at line       (11)keepends])        boundaries.s.startswith      return true if s starts with the specified prefix,

Lines 1–500 of 2279.