设为首页 收藏本站
查看: 416|回复: 0

[经验分享] Python 2.5 Quick Reference

[复制链接]

尚未签到

发表于 2017-4-25 10:11:02 | 显示全部楼层 |阅读模式

DSC0000.png
 
Python 2.5 Quick Reference
收藏


  
<script type="text/javascript">
document.body.oncopy = function() {
if (window.clipboardData) {
setTimeout(function() {
var text = clipboardData.getData(&quot;text&quot;);
if (text &amp;&amp; text.length &gt; 300) {
text = text + &quot;\r\n\n本文来自CSDN博客,转载请标明出处:&quot; + location.href;
clipboardData.setData(&quot;text&quot;, text);
}
}, 100);
}
}
</script><script type="text/javascript">                        function StorePage() { d = document; t = d.selection ? (d.selection.type != 'None' ? d.selection.createRange().text : '') : (d.getSelection ? d.getSelection() : ''); void (keyit = window.open('http://www.365key.com/storeit.aspx?t=' + escape(d.title) + '&amp;u=' + escape(d.location.href) + '&amp;c=' + escape(t), 'keyit', 'scrollbars=no,width=475,height=575,left=75,top=20,status=no,resizable=yes')); keyit.focus(); }</script>
  Style chooser: Modern
, Modern Black&White
, Classic
, High contrast
or Printing


[Hint
: Use styles Modern
Black & White or Printing to print. If you get problems, try
printing the
PDF versions

instead]



<!--  SUMMARY -->

Contents




  • Front matter

  • Invocation
    Options


  • Environment
    variables


  • Lexical entities
    : keywords
    , identifiers
    , string literals
    , boolean
    constants
    , numbers
    ,
    sequences
    , dictionaries
    , operators

  • Basic types
    and their operations:
    None
    ,
    bool
    , Numeric types
    , sequence types
    , list
    , dictionary
    , string
    , file
    , set
    , date/time

  • Advanced types

  • Statements
    :
    assignment
    , conditional
    expressions
    , control
    flow
    , exceptions
    ,
    name space
    , function def
    , class def

  • Iterators
    ;
    Generators
    ;
    Descriptors
    ;
    Decorators

  • Built-in
    Functions


  • Built-in
    Exceptions


  • Standard methods
    & operators redefinition

    in user-created Classes

  • Special informative
    state attributes

    for some types

  • Important modules
    : sys
    , os
    , posix
    , posixpath
    , shutil
    , time
    , string
    , re
    ,
    math
    , getopt

  • List of
    modules

    in the base distribution

  • Workspace exploration
    and idiom hints

  • Python mode for Emacs
<!--  FRONT STUFF -->
Front matter

  Version 2.5 (What's
new?
)

Check updates at http://rgruet.free.fr/#QuickRef
.

Please report
errors, inaccuracies and suggestions to Richard Gruet
(pqr at rgruet.net).

<!--  LICENSE CREATIVE COMMONS -->

Creative Commons License.


Last modified on <!--  #BeginDate format:Am1 -->August 16, 2009<!--  #EndDate -->

14 Dec 2006,
upgraded by Richard Gruet for Python 2.5

17 Feb 2005,
upgraded by Richard Gruet for Python 2.4

03 Oct 2003,
upgraded by Richard Gruet for Python 2.3

11 May 2003, rev 4
upgraded by Richard Gruet for
Python 2.2 (restyled by Andrei
)
7 Aug 2001
upgraded by Simon Brunning
for Python 2.1
16 May 2001
upgraded by Richard Gruet
and Simon Brunning
for Python 2.0
18 Jun 2000
upgraded
by Richard Gruet
for Python 1.5.2
30 Oct 1995
created
by Chris Hoffmann
for Python
1.3   Color coding:


Features added in 2.5 since 2.4

Features added in 2.4 since 2.3

Features added in 2.3 since 2.2

Features added in 2.2 since 2.1


  Originally based on:


  • Python Bestiary, author: Ken Manheimer

  • Python
    manuals
    , authors: Guido van Rossum
    and Fred Drake
  • python-mode.el, author: Tim
    Peters
  • and the readers of comp.lang.python
<!--  LINKS -->  Useful links :




  • Python's nest
    : http://www.python.org

  • Official documentation
    : http://www.python.org/doc/
      [Module
    index

    ; Language Reference
    ]

  • Other doc & free books
    : FAQs
    , Faqts
    , Dive into Python
    , Python
    Cookbook
    , Thinking in Python
    , Text processing in Python

  • Getting started
    : Official
    site
    , 7mn to Hello World (windows)

  • Topics
    : Databases
    ,
    Web
    programming
    , XML
    , Web Services
    , Parsers
    ,
    Scientific Computing
    , GUI
    programming
    , Distributing

  • Where to find packages
    : Easy Install
    , Python Package Index (PyPI)
    , Vaults of Parnassus
    ,
    SourceForge (search
    "python")
    , Python
    Eggs
    , O'Reilly
    Python DevCenter
    , Starship Python

  • Wiki
    : moinmoin

  • Newsgroups
    : comp.lang.python
    and comp.lang.python.announce

  • Misc pages
    : Daily Python URL
    ,
    Kevin Altis' WebLog
    ,
    PEAK

  • Python Development
    : http://www.python.org/dev/

  • Jython
    - Java implementation of Python: http://www.jython.org/

  • IronPython
    - Python on .Net: http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython

  • ActivePython
    : http://www.ActiveState.com/ASPN/Python/

  • Help desk
    : help@python.org
  • 2 excellent Python reference books
    : Python Essential Reference
    by David Beazley &
    Guido Van Rossum (Other New Riders) and Python in a nutshell
    by Alex martelli (O'Reilly).

  • Python 2.4 Reference Card (cheatsheet)
    by Laurent Pointal, designed for printing (15 pages).

  • Online Python 2.2 Quick Reference
    by the New Mexico
    Tech Computer Center.



Tip
: From within the Python interpreter,
type help
, help(object
)
or help("name
")
to get help.

<!--  INVOCATION OPTIONS -->

Invocation Options



python
[w
] [-dEhim
OQStuUvVWxX?] [-c command
| scriptFile
| - ] [args
]
    (pythonw
does not
open a terminal/console; python does)

Invocation Options

Option
Effect

-d
Output parser debugging information (also PYTHONDEBUG=x)


-E
Ignore environment variables (such as PYTHONPATH)


-h
Print a help message and exit (formerly -?)


-i
Inspect interactively after running script (also PYTHONINSPECT=x)
and force prompts, even if stdin appears not to be a terminal.


-m module

Search for module
on sys.path
and runs the
module as a script. (Implementation improved in
2.5: module runpy
)



-O
Optimize generated bytecode (also PYTHONOPTIMIZE=x). Asserts are
suppressed.


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


-U
Force Python to interpret all string literals as Unicode literals.


-v
Verbose (trace import statements) (also PYTHONVERBOSE=x).


-V
Print the Python version number and exit.


-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




-X


Disable
class based built-in exceptions (for backward compatibility management
of exceptions)



-c command

Specify the command to execute (see next section). This terminates
the option list (following options are passed as arguments to the
command).



scriptFile

The name of a python file (.py) to execute. Read from stdin.





-

Program read from stdin (default; interactive mode if a tty).



args

Passed to script or command (in sys.argv[1:]
)


 
If no scriptFile or command, Python enters interactive mode.


  • Available IDEs
    in std distrib: IDLE
    (tkinter based, portable), Pythonwin
    (on Windows).
    Other free IDEs: IPython
    (enhanced interactive Python shell), Eric
    , SPE
    , BOA constructor
    , PyDev
    (Eclipse
    plugin).
  • Typical python module header
    :

    #!/usr/bin/env python
    # -*-
    coding: latin1 -*-


    Since 2.3 the encoding
    of a Python source
    file must be declared as one of the two first lines (or defaults to 7
    bits Ascii

    ) [PEP-0263
    ], with the
    format:


    # -*- coding: encoding
    -*-

    Std encodings
    are defined here
    ,
    e.g. ISO-8859-1 (aka latin1), iso-8859-15 (latin9), UTF-8... Not all
    encodings supported, in particular UTF-16 is not supported.
  • It's now a syntax error
    if a module
    contains string literals with 8-bit characters but doesn't have an
    encoding declaration (was a warning before).
  • Since 2.5, from __future__ import feature

    statements must be declared at beginning
    of source
    file.

  • Site customization
    : File sitecustomize.py
    is automatically loaded by Python if it exists in the Python path
    (ideally located in ${PYTHONHOME}/lib/site-packages/
    ).

  • Tip:
    when launching a Python script on Windows,

    <pythonHome>\python myScript.py args ...
    can be reduced to :
    myScript.py args ...
    if
    <pythonHome> is in the PATH envt variable, and further reduced to :

    myScript args ...
    provided that .py;.pyw;.pyc;.pyo
    is added to the PATHEXT
    envt variable.

<!--  ENVIRONMENT VARIABLES -->
Environment variables


Environment variables

Variable
Effect

PYTHONHOME
Alternate prefix
directory (or prefix
;exec_prefix
).
The default module search path uses prefix
/lib



PYTHONPATH

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 !

On
Windows Python first searches for Registry key HKEY_LOCAL_MACHINE\Software\Python\PythonCore\x.y
\PythonPath
(default value). You can create a key named after your application with
a default string value giving the root directory path of your appl.


Alternatively,
you can create a text file with a .pth
extension,
containing the path(s), one per line, and put the file somewhere in the
Python search path (ideally in the site-packages/
directory). It's better to create a .pth for each application, to make
easy to uninstall them.




PYTHONSTARTUP
If this is the name of a readable file, the Python commands in that
file are executed before the first prompt is displayed in interactive
mode (no default).


PYTHONDEBUG
If non-empty, same as -d option


PYTHONINSPECT
If non-empty, same as -i option


PYTHONOPTIMIZE
If non-empty, same as -O option


PYTHONUNBUFFERED
If non-empty, same as -u option


PYTHONVERBOSE
If non-empty, same as -v option


PYTHONCASEOK
If non-empty, ignore case in file/module names (imports)
<!-- NOTABLE LEXICAL ENTITIES -->
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      with
def       finally   in        print     yield



  • (List of keywords available in std module: keyword
    )
  • Illegitimate Tokens (only valid in strings): $ ?
    (plus @
    before 2.4)
  • 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 -->
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).
<!--  STRING LITERALS -->
String literals

  Two flavors: str
(standard 8 bits locale-dependent
strings, like ascii, iso 8859-1, utf-8, ...) and unicode
(16 or 32 bits/char in utf-16 mode or 32 bits/char in utf-32 mode); one
common ancestor basestring
.


Literal


"
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

Escape
Meaning


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



\x
hh

char with hex value hh




\b

Backspace (BS)



\t

Horizontal Tab (TAB)



\u
xxxx

Character with 16-bit hex value xxxx
(unicode only)



\U
xxxxxxxx

Character with 32-bit hex value xxxxxxxx
(unicode only)



\N{
name
}

Character named in the Unicode database (unicode only), e.g. u'\N{Greek
Small Letter Pi}'
<=> u'\u03c0'.


(Conversely,
in module unicodedata, unicodedata.name(u'\u03c0') == 'GREEK
SMALL LETTER PI'
)



\AnyOtherChar


left as-is, including the backslash, e.g. str('\z') == '\\z'



  • 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.
<!--  BOOLEAN CONSTANTS -->
Boolean
constants (since 2.2.1)





  • True

  • False



In 2.2.1, True and False are integers 1 and 0. Since
2.3, they are of new type bool
.

<!--  NUMBERS -->

Numbers





  • Decimal integer
    : 1234, 1234567890546378940L
    (or l)

  • Octal
    integer: 0
    177, 0
    177777777777777777L
    (begin with a 0
    )

  • Hex
    integer: 0x
    FF, 0X
    FFFFffffFFFFFFFFFFL
    (begin with 0x
    or 0X
    )

  • Long
    integer (unlimited precision):
    1234567890123456L
    (ends with L
    or l
    )
    or long(
    1234)

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


Integers and long integers are unified
starting from release 2.2 (the L
suffix is no longer
required)

<!--  SEQUENCES -->

Sequences





  • Strings
    (types str
    and unicode
    )
    of length 0, 1, 2 (see above
    )


      '', '1', "12", 'hello\n'

  • Tuples
    (type tuple
    ) of length 0, 1, 2,
    etc:

      ()
    (1,
    ) (1,2) # parentheses
    are optional if len > 0

  • Lists
    (type list
    ) of length 0, 1, 2,
    etc:

      []
    [1] [1,2]



  • Indexing is 0
    -based. Negative indices (usually)
    mean count backwards from end of sequence.
  • Sequence slicing [
    starting-at-index
    :
    but-less-than-index
    [ : step]

    ]
    .
    Start defaults to 0, end to len(sequence), step
    to 1
    .
      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.
      a[::2] == (0, 2, 4, 6) # Only even numbers.
    a[::-1] = (7, 6, 5, 4, 3 , 2, 1, 0) # Reverse order.
<!--  DICTIONARIES -->
Dictionaries (Mappings)



Dictionaries
(type dict
) of length 0, 1, 2, etc: {}
{1
: 'first'} {1 : 'first', 'two': 2, key
:value
}
  Keys must be of a hashable
type; Values can be any type.

<!--  OPERATORS -->

Operators and their
evaluation order


Operators and their evaluation order

Highest
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
mult, division, modulo


x+
y x-
y
addition, substraction


x<<y   x>>y
Bit shifting


x&
y
Bitwise and


x^
y
Bitwise exclusive or


x|
y
Bitwise or


x<
y  x<=
y  x>

x>=
y  x==
y x!=
y  x<>
y

x
is
y   x is not
y

x in
s   x not in
s
Comparison, 

identity, 

membership



not
x
boolean negation


x and
y
boolean and


x or
y
boolean or


Lowest

lambda
args
: expr

anonymous function


  • Alternate names are defined in module operator (e.g. __add__
    and add
    for +)
  • Most operators are overridable
<!--  BASIC TYPES AND THEIR OPERATIONS -->
Basic types and their
operations


<!--  COMPARISONS -->
Comparisons (defined between any
types)


Comparisons

Comparison
Meaning
Notes



<

strictly less than

(1)







<=

less than or equal to
 



>

strictly greater than
 



>=

greater than or equal to
 



==

equal to
 



!=
or <>

not equal to
 



is

object identity

(2)





is not

negated object identity

(2)


  Notes
:


  • Comparison behavior can be overridden for a given class by defining
    special method __cmp__
    .
  • (1) X < Y < Z < W has expected meaning, unlike C
  • (2) Compare object identities (i.e. id
    (object)),
    not object values.
<!--  NONE -->
None





  • None
    is used as default return value on functions.
    Built-in single object with type NoneType
    . Might become a
    keyword in the future.
  • Input that evaluates to None
    does not print when
    running Python interactively.
  • None is now a constant
    ; trying to
    bind a value to the name "None" is now a syntax error.


<!--  BOOLEAN OPERATORS -->

Boolean operators


Boolean values and operators

Value or Operator
Evaluates to
Notes


built-in bool
(expr
)

True
if expr
is true, False
otherwise.

see True, False






None
, numeric zeros, empty sequences and mappings
considered False
 


all other values
considered True
 



not
x


True
if x
is False
, else False

 



x
or
y

if x
is False
then y
, else x


(1)







x
and
y

if x
is False
then x
, else y


(1)




  Notes
:


  • Truth testing behavior can be overridden for a given class by
    defining special method __nonzero__
    .
  • (1) Evaluate second arg only if necessary to determine outcome.
<!--  NUMERIC TYPES -->
Numeric types


Floats, integers, long integers, Decimals
.




  • Floats (type float
    ) are implemented with C doubles.
  • Integers (type int
    ) are implemented with C longs
    (signed 32 bits, maximum value is sys.maxint
    )
  • Long integers (type long
    ) have unlimited size (only
    limit is system resources).
  • Integers and long integers are unified
    starting from release 2.2 (the L
    suffix is no longer
    required). int()
    returns a long
    integer instead of raising OverflowError

    . Overflowing operations such as 2<<32
    no longer trigger FutureWarning
    and return a long integer.

  • Since 2.4, new type Decimal
    introduced
    (see module: decimal
    )
    to compensate for some limitations of the floating point type, in
    particular with fractions. Unlike floats, decimal numbers can be
    represented exactly; exactness is preserved in calculations; precision
    is user settable via the Context
    type [PEP 327
    ].


<!--  OPERATORS ON ALL NUMERIC TYPES -->
Operators on all numeric types

Operators on all numeric types

Operation
Result


abs
(x
)
the absolute value of x




int
(x
)

x
converted to integer



long
(x
)

x
converted to long integer



float
(x
)

x
converted to floating point


-x


x
negated


+x


x
unchanged



x
+ y

the sum of x
and y




x
- y

difference of x
and y




x
* y

product of x
and y




x
/ y

true division of x by y: 1/2 -> 0.5 (1)



x
// y

floor division operator: 1//2 -> 0 (1)



x
% y


x
modulo y




divmod
(x
, y
)
the tuple (x
//y
, x
%y
)



x
** y


x
to the power y
(the same as pow
(x
,y
))
  Notes
:


  • (1) /
    is still a floor
    division (1/2 == 0) unless validated by a from __future__ import
    division
    .
  • classes may override methods __truediv__
    and __floordiv__
    to redefine these operators.
<!--  BIT OPERATORS ON INTEGERS AND LONG INTEGERS -->Bit operators on integers and long integers

Bit operators

Operation
Result

~x

the bits of x
inverted



x
^ y

bitwise exclusive or of x
and y




x
& y

bitwise and of x
and y




x
| y

bitwise or of x
and y




x
<< n


x
shifted left by n
bits



x
>> n


x
shifted right by n
bits
<!--  COMPLEX NUMBERS -->Complex Numbers


  • Type complex
    , 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 -->Numeric exceptions


TypeError

raised on application of
arithmetic operation to non-number

OverflowError

numeric
bounds exceeded

ZeroDivisionError

raised
when zero second argument of div or modulo op
<!--  OPERATIONS ON ALL SEQUENCE TYPES -->
Operations on all
sequence types (lists, tuples, strings)


Operations on all sequence types

Operation
Result
Notes



x
in
s


True
if an item of s
is equal to x
,
else False


(3)





x
not in
s


False
if an item of s
is equal to x
,
else True


(3)





s1
+
s2

the concatenation of s1
and s2

 



s
*
n
, n
*
s


n
copies of s
concatenated

 







s
[
i
]


i
'th item of s
, origin 0

(1)





s
[
i
:
j
]

s
[
i
:

j

:
step
]


Slice of s
from i
(included) to j
(excluded).
Optional step
value, possibly negative
(default: 1).


(1), (2)





len
(s
)
Length of s

 



min
(s
)
Smallest item of s


 







max
(s
)
Largest item of s


 







reversed
(s
)
[2.4] Returns an iterator
on s
in reverse order. s
must be a sequence, not an
iterator (use reversed(list(s))
in this case. [PEP 322]


 







sorted
(iterable
[, cmp
]

  [,
cmp=cmpFct
]

  [, key=keyGetter
]

  [, reverse=bool
])

[2.4] works like the new in-place list.sort()
, but sorts a new
list created from the iterable
.

 




  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 with index k
    such that i<= k
    < j

    .

    If i
    or j
    is greater than len(s
    ),
    use len(s
    ). If j
    is omitted, use len(s
    ). If i
    is greater than or equal to j
    , the slice is empty.
  • (3) For strings: before 2.3, x must be a single
    character string; Since 2.3, x in s
    is True if x is a substring
    of s.
<!--  OPERATIONS ON MUTABLE SEQUENCES -->
Operations on mutable sequences (type list
)


Operations on mutable sequences

Operation
Result
Notes



s
[
i
]
=
x

item i
of s
is replaced by x

 



s
[i
:j
[:step
]
]
=
t

slice of s
from i
to j
is replaced by t

 



del
s
[i
:j
[:step
]
]
same as s
[i
:j
] = []
 



s
.append
(x
)
same as s
[len(s
) : len(s
)] = [x
]
 



s
.extend
(x
)
same as s
[len(s
):len(s
)]= x


(5)







s
.count
(x
)
returns number of i
's for which s
[i
] == x

 



s
.index
(x
[,
start
[, stop
]]
)
returns smallest i
such that s
[i
]==x
.
start
and stop
limit search to
only part of the list.


(1)





s
.insert
(i
, x
)
same as s
[i
:i
] = [x
] if i
>=
0. i
== -1 inserts before
the last element.

 



s
.remove
(x
)
same as del s
[s
.index(x
)]

(1)





s
.pop
([
i
]
)

same as x = s; del s; return x

(4)





s
.reverse
()
reverses the items of s
in place

(3)






s

.sort
([
cmp

]

)
s
.sort
([cmp=cmpFct
]

  [,
key=keyGetter
]

  [, reverse=bool
])

sorts the items of s
in place

(2), (3)


  Notes
:


  • (1) Raises a ValueError
    exception when x
    is
    not found in s
    (i.e. out of range).
  • (2) The sort() method takes an optional argument cmp
    specifying a comparison function takings 2 list items and returning -1,
    0, or 1 depending on whether the 1st argument is considered smaller
    than, equal to, or larger than the 2nd argument. Note that this slows
    the sorting process down considerably. Since 2.4,
    the cmp
    argument may be specified as a keyword, and 2
    optional keywords args are added: key
    is a fct that takes a
    list item and returns the key to use in the comparison (faster
    than cmp
    ); reverse
    : If True, reverse the
    sense of the comparison used.


    Since Python 2.3, the sort is
    guaranteed "stable". This means that two entries with equal keys will be
    returned in the same order as they were input. For example, you can
    sort a list of people by name, and then sort the list by age, resulting
    in a list sorted by age where people with the same age are in
    name-sorted order.
  • (3) The sort()
    and reverse()
    methods modify
    the list in place
    for economy of space when sorting or
    reversing a large list. They don't return the sorted or reversed list
    to remind you of this side effect.
  • (4) The pop()
    method is not supported by mutable
    sequence types other than lists. The optional argument i defaults to -1,
    so that by default the last item is removed and returned.
  • (5) Raises a TypeError
    when x is not a list object.
<!--  OPERATION ON DICTIONARIES -->
Operations on mappings /
dictionaries (type dict
)


Operations on mappings
Operation
Result
Notes



len
(d
)
The number of items in d

 



dict
()
dict
(**kwargs
)
dict
(iterable
)
dict
(d)


Creates an empty dictionary.
Creates a
dictionary init with the keyword args kwargs
.

Creates a
dictionary init with (key, value) pairs provided by iterable
.

Creates
a dictionary which is a copy of dictionary d
.

 



d
.fromkeys
(iterable
, value
=None)
Class method to create a dictionary with keys provided by iterator
,
and all values set to value
.
 



d
[
k
]

The item of d
with key k


(1)





d
[k
] =
x
Set d
[k
] to x

 



del
d
[k
]
Removes d
[k
] from d


(1)





d
.clear
()
Removes all items from d

 



d
.copy
()
A shallow copy of d

 



d
.has_key
(k
)
k
in
d



True
if d
has key k
, else False

 



d
.items
()
A copy of d
's list of (key, item) pairs

(2)





d
.keys
()
A copy of d
's list of keys

(2)





d1
.update
(d2
)

for k, v in d2
.items(): d1
[k] = v

Since 2.4, update
(**kwargs
)
and update
(iterable
) may also be used.





d
.values
()
A copy of d
's list of values

(2)





d
.get
(k
, defaultval
)
The item of d
with key k


(3)





d
.setdefault
(k
[,defaultval
])

d
[k
] if k
in d
, else defaultval
(also
setting it)

(4)




d.iteritems
()
Returns an iterator
over (key, value) pairs
.
 


d.iterkeys
()
Returns an iterator
over the mapping's keys
.
 


d.itervalues
()
Returns an iterator
over the mapping's values
.
 



d
.pop
(k
[, default
])
Removes key k
and returns the corresponding value. If key
is not found, default
is returned if given, otherwise KeyError
is raised.
 



d
.popitem
()

Removes and returns an arbitrary (key, value) pair from d


 


  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) 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.
  • (4) Never raises an exception if k
    is not
    in the map, instead 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.
<!--  OPERATIONS ON STRINGS -->
Operations
on strings (types str
& unicode
)


These string methods largely (but not completely)
supersede the functions available in the string
module.

The str
and unicode
types
share a common base class basestring
.

[table]
Operations on strings
[tr]
Operation
Result
Notes

[/tr][tr]
[td]
s.
capitalize
()
[/td]
[td]Returns a copy of s
with its first character capitalized,
and the rest of the characters lowercased. [/td]
[td]  [/td]
[/tr]
[tr]
[td]
s.
center
(width
[
,
fillChar=' '
]
)[/td]
[td]Returns a copy of s
centered in a string of length width
,
surrounded by the appropriate number of fillChar
characters. [/td]
[td]
(1)

[/td]
[/tr]
[tr]
[td]
s.
count
(sub
[
,
start

[
, end
]]
)
[/td]
[td]Returns the number of occurrences of substring sub
in
string s
. [/td]
[td]
(2)

[/td]
[/tr]
[tr]
[td]
s.
decode
(
[
encoding
[
,
errors

]]
)
[/td]
[td]Returns a unicode
string representing the decoded
version of str
s
, using the given codec
(encoding). Useful when reading from a file or a I/O function that
handles only str
. Inverse of encode
. [/td]
[td]
(3)

[/td]
[/tr]
[tr]
[td]
s.
encode
(
[
encoding
[
,
errors

]]
)
[/td]
[td]Returns a str
representing an encoded version of s
.
Mostly used to encode a unicode
string to a str
in order to print it or write it to a file (since these I/O functions
only accept str
), e.g. u'légère'.encode('utf8')
.
Also used to encode a str
to a str
, e.g. to
zip (codec 'zip') or uuencode (codec 'uu') it. Inverse of decode
.
[/td]
[td]
(3)

[/td]
[/tr]
[tr]
[td]
s.
endswith
(suffix
[
,
start

[
, end
]]
)
[/td]
[td]Returns True
if s
ends with the specified suffix
,
otherwise return false. Since 2.5 suffix
can also be a tuple
of strings to try.
[/td]
[td]
(2)

[/td]
[/tr]
[tr]
[td]
s.
expandtabs
(
[
tabsize
]
)
[/td]
[td]Returns a copy of s
where all tab characters are expanded
using spaces. [/td]
[td]
(4)

[/td]
[/tr]
[tr]
[td]
s.
find
(sub
[
,start
[
,end
]]
)
[/td]
[td]Returns the lowest index in s
where substring sub
is found. Returns -1
if sub
is not found. [/td]
[td]
(2)

[/td]
[/tr]
[tr]
[td]
s.
index
(sub
[
,
start

[
, end
]]
)
[/td]
[td]like find()
, but raises ValueError
when the substring is not found. [/td]
[td]
(2)

[/td]
[/tr]
[tr]
[td]
s.
isalnum
()
[/td]
[td]Returns True
if all characters in s
are
alphanumeric, False
otherwise. [/td]
[td]
(5)

[/td]
[/tr]
[tr]
[td]
s.
isalpha
()
[/td]
[td]Returns True
if all characters in s
are
alphabetic, False
otherwise. [/td]
[td]
(5)

[/td]
[/tr]
[tr]
[td]
s.
isdigit
()
[/td]
[td]Returns True
if all characters in s
are digit
characters, False
otherwise. [/td]
[td]
(5)

[/td]
[/tr]
[tr]
[td]
s.
islower
()
[/td]
[td]Returns True
if all characters in s
are
lowercase, False
otherwise. [/td]
[td]
(6)

[/td]
[/tr]
[tr]
[td]
s.
isspace
()
[/td]
[td]Returns True
if all characters in s
are
whitespace characters, False
otherwise.[/td]
[td]
(5)

[/td]
[/tr]
[tr]
[td]
s.
istitle
()
[/td]
[td]Returns True
if string s
is a titlecased
string, False
otherwise. [/td]
[td]
(7)

[/td]
[/tr]
[tr]
[td]
s.
isupper
()
[/td]
[td]Returns True
if all characters in s
are
uppercase, False
otherwise. [/td]
[td]
(6)

[/td]
[/tr]
[tr]
[td]
separator.
join
(seq)
[/td]
[td]Returns a concatenation of the strings in the sequence seq
,
separated by string separator
, e.g.: ",".join(['A', 'B',
'C'])
-> "A,B,C"
[/td]
[td]
 

[/td]
[/tr]
[tr]
[td]
s.
ljust/rjust/center
(width
[, fillChar=' '
]
)[/td]
[td]Returns s

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-368961-1-1.html 上篇帖子: 【Python】Python三目运算,and or陷阱 下篇帖子: [Python]入门教程(三):Python中的控制流
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表