summaryrefslogtreecommitdiffstats
path: root/Misc
diff options
context:
space:
mode:
Diffstat (limited to 'Misc')
-rw-r--r--Misc/cheatsheet127
1 files changed, 67 insertions, 60 deletions
diff --git a/Misc/cheatsheet b/Misc/cheatsheet
index a4d96e2..828b54e 100644
--- a/Misc/cheatsheet
+++ b/Misc/cheatsheet
@@ -1,7 +1,7 @@
- Python 2.0 Quick Reference
-
+ 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.2
from V1.3 ref
@@ -19,32 +19,14 @@ 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.org
-Resources: http://starship.python.net/ and http://www.vex.net/parnassus/
+Resources: http://starship.python.net/
+ http://www.vex.net/parnassus/
+ http://aspn.activestate.com/ASPN/Cookbook/Python
+FAQ: http://www.python.org/cgi-bin/faqw.py
Full documentation: http://www.python.org/doc/
-An excellent Python reference book: Python Essential Reference by David Beazley
-(New Riders)
-
-
-Contents
-
- * Invocation Options
- * Environment Variables
- * Lexical Entities : keywords, identifiers, strings, numbers, sequences,
- dictionaries, operators
- * Basic Types And Their Operations
- * Advanced Types
- * Statements
- * 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 base distribution
- * Workspace Exploration And Idiom Hints
- * Python Mode for Emacs
- * The Python Debugger
-
+Excellent reference books:
+ Python Essential Reference by David Beazley (New Riders)
+ Python Pocket Reference by Mark Lutz (O'Reilly)
Invocation Options
@@ -53,18 +35,21 @@ python [-diOStuUvxX?] [-c command | script | - ] [args]
Invocation Options
Option 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 (set __debug__ = 0 =>s suppresses asserts)
+-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).
--U Force Python to interpret all string literals as Unicode literals.
-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
-[DEL:-X [DEL:Disable class based built-in exceptions (for backward
-:DEL] compatibility management of exceptions):DEL]
-? Help!
-c Specify the command to execute (see next section). This terminates the
command option list (following options are passed as arguments to the command).
@@ -115,7 +100,7 @@ Keywords
assert elif from lambda return
break else global not try
class except if or while
- continue exec import pass
+ continue exec import pass yield
def finally in print
* (list of keywords in std module: keyword)
@@ -174,9 +159,9 @@ Strings
Numbers
Decimal integer: 1234, 1234567890546378940L (or l)
- Octal integer: 0177, 0177777777777777777L (begin with a 0)
- Hex integer: 0xFF, 0XFFFFffffFFFFFFFFFFL (begin with 0x or 0X)
- Long integer (unlimited precision): 1234567890123456L (ends with L 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)
@@ -206,8 +191,12 @@ a = (0,1,2,3,4,5,6,7)
Dictionaries (Mappings)
- Dictionary of length 0, 1, 2, etc:
- {} {1 : 'first'} {1 : 'first', 'next': 'second'}
+ {} # 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
@@ -235,7 +224,10 @@ Highest Operator Comment
Lowest lambda args: expr anonymous function
Alternate names are defined in module operator (e.g. __add__ and add for +)
-Most operators are overridable
+Most operators are overridable.
+
+Many of binary operators support augmented assignment:
+ x += 1 # Same as x = x + 1
Basic Types and Their Operations
@@ -256,6 +248,9 @@ is not negated object identity (2)
Notes :
Comparison behavior can be overridden for a given class by defining special
method __cmp__.
+ The above comparisions return True or False which are of type bool
+(a subclass of int) and behave exactly as 1 or 0 except their type and
+that 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.
@@ -344,6 +339,7 @@ Operations on all sequence types (lists, tuples, strings)
Operation Result Notes
x in s 1 if an item of s is equal to x, else 0
x not in s 0 if an item of s is equal to x, else 1
+for x in s: loops over the sequence
s + t the concatenation of s and t
s * n, n*s n copies of s concatenated
s[i] i'th item of s, origin 0 (1)
@@ -351,6 +347,7 @@ s[i:j] slice of s from i (included) to j (excluded) (1), (2)
len(s) length of s
min(s) smallest item of s
max(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,
@@ -370,12 +367,12 @@ s[i] =x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by t
del s[i:j] 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) return number of i's for which s[i] == x
+s.extend(x) same as s[len(s):len(s)]= x
s.index(x) return smallest i such that s[i] == x (1)
s.insert(i, x) same as s[i:i] = [x] if i >= 0
-s.remove(x) same as del s[s.index(x)] (1)
s.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)
@@ -391,12 +388,8 @@ considered smaller than, equal to, or larger than the 2nd
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) [New 1.5.2] The pop() method is experimental and not supported by
-other mutable sequence types than lists.
- The optional argument i defaults to -1, so that by default the last
+ (4) [New 1.5.2] The optional argument i defaults to -1, so that by default the last
item is removed and returned.
- (5) [New 1.5.2] Experimental ! Raises an exception when x is not a list
-object.
@@ -410,12 +403,18 @@ d[k] = x set d[k] to x
del d[k] remove d[k] from d (1)
d.clear() remove all items from d
d.copy() a shallow copy of d
+d.get(k,defaultval) the item of d with key k (4)
d.has_key(k) 1 if d has key k, else 0
d.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.get(k,defaultval) the item of d with key k (4)
+d.pop(k) remove d[k] and return its value
+d.popitem() remove and return an arbitrary (6)
+ (key, item) pair
d.setdefault(k,defaultval) the item of d with key k (5)
Notes :
@@ -431,6 +430,9 @@ d.setdefault(k,defaultval) the item of d with key k (5)
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
@@ -446,30 +448,33 @@ 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[,errors current default string encoding. (3)
-]])
+ 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.
+ [,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)
+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)
+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)
+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.
@@ -503,6 +508,8 @@ s.title() uppercase characters, all remaining cased characters
s.translate(table return a copy of s mapped through translation table (12)
[,deletechars]) table.
s.upper() return a copy of s converted to uppercase.
+s.zfill(width) return a string padded with zeroes on the left and
+ sliding a minus sign left if necessary. never truncates.
Notes :
(1) Padding is done using spaces.