You are on page 1of 2

Python 2.5 Reference Card 1.

3 Dictionaries (Mappings) rsplit(s,m), splitlines(ke)


d={'x':42, 'y':3.14, 'z':7} dict creation padding: center(w,c), ljust(w,c), lstrip(cs),
(c) 2007 Michael Goerz <goerz@physik.fu-berlin.de>
http://www.physik.fu-berlin.de/~goerz/ d['x'] get entry for 'x' rjust(w,c), rstrip(cs), strip(cs), zfill(w),
Information taken liberally from the python documentation and various other sources. len(d) number of keys expandtabs(ts)
You may freely modify and distribute this document. checking: isalnum, isalpha, isdigit, islower, isspace,
del(d['x']) delete entry from dict
d.copy() create shallow copy istitle, isupper
1 Variable Types d.has_key(k) does key exist? String Constants: import string
1.1 Numbers d.items() list of all items digits, hexdigits, letters, lowercase, octdigits,
42 052 0x2A 42L 052L 0x2AL 42 (dec, oct, hex, short/long) d.keys() list of all keys printable, punctuation, uppercase, whitespace
0.2 .8 4. 1.e10 1.0e-7 floating point value d.values() list of all values Regexes: import re
z = 5.0 – 2.0J; complex number i=d.iteritems(); i.next() iterator over items r=re.compile(r'rx',re.ILMSUX) comile 'rx' as regex
z = complex(real, imag) complex number i=d.iterkeys(); i.next() iterator over keys (?P<id>...) named group
z.real; z.imag real and imag part of z i=d.itervalues(); i.next() iterator over values m=r.match(s,b,e) full match
True; False constants for boolean values d.get(k,x) get entry for k, or return x re.match(r'(?iLmsux)rx',s) direct regex usage
abs(n) absolute value of n d.clear() remove all items m=r.search(s,b,e) partial match
divmod(x, y) (x/y, x%y) d.setdefault(k,x) return d[k] or set d[k]=x l=r.split(s,ms) split and return list
hex(n) create hex string d.popitem() return and delete an item l=r.findall(string) list of all matched groups
oct(n) create octal string 1.4 Sets s=r.sub(s,r,c) replace c counts of s with r
ord(c) unicode code point of char s=set(s); fs=frozenset(s) create set (s,n)=r.subn(s,r,c) n is number of replacements
round(x,n) round x to n decimal places fs.issubset(t); s<=t all s in t? s=re.escape(s) escape all non-alphanumerics
cmp(x,y) x<y: -1, x==y: 0, x>y: 1 fs.issuperset(t); s>=t all t in s? m.start(g);m.span(g);m.end(g) group-match delimiters
coerce(x, y) (x,y), make same type fs.union(t); s|t all elements from s and t m.expand(s) replace \1 etc. with matches
pow(x,y,z) (x**y) % z fs.intersection(t); s&t m.group(g); m.group("name") matched group no. g
elements both in s and t
float("3.14") float from string m.groups() list of groups
fs.difference(t); s-t all s not in t
int("42", base) int from string m.groupdict() dict of named groups
fs.symmetric_difference(t); all either s or t
import math; import cmath more math functions s^t
import random; random number generators
1.2 Sequences (lists are mutable, tuples and strings are immutable)
fs.copy()
s.update(t); s|=t
shallow copy of s 2 Basic Syntax
add elements of t if expr: statements conditional
s=l=[1, "bla", [1+2J, 1.4], 4] list creation s.intersection_update(t); s&=t keep only what is also in t elif expr: statements
s=t=(1, "bla", [1+2J, 1.4], 4) tuple creation s.difference_update(t); s-=t remove elements of t else: statements
l=list(t); t=tuple(l) list/tuple conversion s.symmetric_differ...(t); s^=t keep only symm. difference if a is b : ... object identity
l=range(1000) list of integers (0-999) s.add(x) add x to fs if a == 1 value identity
s=xrange(1000) immut. xrange-sequence s.remove(x); fs.discard(x); remove x (/ with exception) while expr: statements while loop
i=iter(s); i.next() iterator from sequence s.pop(); return and remove any elem. else: statements run else on normal exit
s[2][0] get list element (1+2J) s.clear(); remove all elements while True: ... if cond: break do... while equivalent
s[-2][-1] get list element (1.4)
s1+s1 sequence concat
1.5 Strings and Regular Expressions for target in iter: statements for loop
"bla"; 'hello "world"' string (of bytes) else: statements
n*s1 repeat s1 n times for key,value in d.items():...
"""bla""", '''bla''' triple quotes for multiline multiple identifiers
s[i:j]; s[i:]; s[:j] slicing (i incl., j excl.) break, continue end loop / jump to next
\ \\ \0 cont., backslash, null char
s[i:j:k] slice with stride k \N{id} \uhhhh \Uhhhhhhhh print "hello world", print without newline
unicode char
s[::2]; s[::-1] every 2nd Element / reverse s \xhh \ooo hex, octal byte [ expr for x in seq lc ] list comprehension
x in s; x not in s is x a member of s? u"Ünic\u00F8de"; u"\xF8" unicode string (of characters) lc = for x in seq / if expr with lc-clauses
len(s) number of elements r"C:\new\text.dat"; ur"\\Ü" raw string (unicode) pass empty statement
min(s); max(s) min/max str(3.14); str(42) string conversion def f(params): statements function definition
l[i:j]=['a','b','c','d'] replace slice "%s-%s-%s" % (42,3.14,[1,2,3]) string formatting def f(x, y=0): return x+y optional parameter
l[i:i]=['a','b'] insert before position i '\t'.join(seq) join sequences with separator def f(*a1, **a2): statements additional list of unnamed,
l.count(x) number of occurances of x s.decode('utf-8') latin-1 string to unicode string dict of named paramters
l.index(x) first index of x, or error u.encode('utf-8') unicode string to utf-8 string def f(): f.variable = 1 ... function attribute
l.append(x) append x at end of l chr(i), unichr(i) char from code point return expression return from function
x=l.pop() pop off last element str(x) string from number/object yield expression make function a generator
l.extend(l2) append l2 at end of l Other String Methods: f(1,1), f(2), f(y=3, x=4) function calls
l.insert(i,x) instert x at pos. i search and replace: find(s,b,e), rfind(s,b,e), global v bind to global variable
l.remove(x) delete first x index(s,b,e), rindex(s,b,e), count(s,b,e), def make_adder_2(a): closure
l.reverse() reverse l endswith(s,b,e), startswith(s,b,e), replace(o,n,m) def add(b): return a+b
l.sort(f) sort using f (default f =cmp) formatting: capitalize, lower, upper, swapcase, title return add
zip(s,t,...) [(s[0],t[0],...),..] splitting: partition(s), rpartition(s), split(s,m), lambda x: x+a lambda expression
compile(string,filename,kind)
eval(expr,globals,locals)
compile string into code object
evaluate expression
assert expression debug assertion
class MyExcept(Exception): ... define user exception
7 Standard Library (almost complete)
String Services: string, re, struct, difflib, StringIO,
exec code in gldict, lcdict compile and execute code raise MyExcept , data raise user exception cStringIO, textwrap, codecs, unicodedata, stringprep,
execfile(file,globals,locals) execute file fpformat
raw_input(prompt)
input(prompt)
input from stdin
input and evaluate
5 System Interaction Data Types: datetime, calendar, collections, heapq,
sys.path module search path bisect, array, sets, sched, mutex, Queue, weakref,
sys.platform operating system UserDict, UserList, UserString, types, new, copy,
sys.stdout, stdin, stderr standard input/output/error pprint, repr
3 Object Orientation and Modules sys.argv[1:] command line parameters Numeric and Math Modules: math, cmath, decimal, random,
import module as alias import module os.system(cmd) system call itertools, functools, operator
from module import name1,name2 load attr. into own namespace os.startfile(f) open file with assoc. program Internet Data Handling: email, mailcap, mailbox, mhlib,
from __future__ import * activate all new features os.popen(cmd, r|w, bufsize) open pipe (file object) mimetools, mimetypes, MimeWriter, mimify, multifile,
reload module reinitialize module os.popen2(cmd, bufsize, b|t) (stdin, stdout) fileobjects rfc822, base64, binhex, binascii, quopri, uu
module.__all__ exported attributes os.popen3(cmd, bufsize, b|t) (stdin, stdout,stderr) Structured Markup Processing Tools: HTMLParser, sgmllib,
module.__name__ module name / "__main__" os.environ['VAR']; os.putenv[] read/write environment vars htmllib, htmlentitydefs, xml.parsers.expat, xml.dom.*,
module.__dict__ module namespace glob.glob('*.txt') wildcard search xml.sax.*, xml.etree.ElementTree
__import__("name",glb,loc,fl) import module by name Filesystem Operations File Formats: csv, ConfigParser, robotparser, netrc,
class name (superclass,...): class definition os module: access, chdir, chmod, chroot, getcwd, getenv, xdrlib
data = value shared class data listdir, mkdir, remove, unlink, removedirs, rename, Crypto Services: hashlib, hmac, md5, sha
def method(self,...): ... methods rmdir, getatime, getmtime, getsize, cmp, cmpfiles, File/Directory Access: os.path, fileinput, stat, statvfs,
def __init__(self, x): constructor dircmp, copy, copy2, copyfile, copyfileobj, copymode, filecmp, tempfile, glob, fnmatch, linecache, shutil,
Super.__init__(self) call superclass constructor copystat, copytree, rmtree, pipe dircache
self.member = x per-instance data
os.path module: abspath, altsep, basename, commonprefix, Compression: zlib, gzip, bz2, zipfile, tarfile
def __del__(self): ... destructor
curdir, defpath, dirname, exists, expanduser, Persistence: pickle, cPickle, copy_reg, shelve, marshal,
__str__, __len__, __cmp__,__ some operator overloaders expandvar, extsep, get[acm]time, getsize, isabs, anydbm, whichdb, dbm, gdbm, dbhash, bsddb, dumbdbm,
__iter__(self): return self use next method for iterator isdir, isfile, islink, ismout, join, lexists,
sqlite3
__call__ call interceptor normcase, normpath, os, pardir, pathsep, realpath, Generic OS services: os, time, optparse, getopt, logging,
__dict__ instance-attribute dictionary samefile, sameopenfile, samestat, sep, split, getpass, curses, platform, errno, ctypes
__getattr__(self, name), get an unknown attribute splitdrive, splitext, stat, walk Optional OS services: select, thread, threading,
__setattr__(self, name, value) set any attribute
command line argument parsing: dummy_thread, dummy_threading, mmap, readline,
callable(object) 1 if callable, 0 otherwise restlist, opts = \ rlcompleter
delattr(object, "name") delete name-attr. from object getopt.getopt(sys.argv[l:],\ Unix specific: posix, pwd, spwd, grp, crypt, dl, termios,
del(object) unreference object/var "s:oh",\ tty, pty, fcntl, posixfile, resource, nis, syslog,
dir(object) list of attr. assoc. with object ["spam=", "other", "help"]) commands
getattr(object, "name", def) get name-attr. from object for o, a in opts: IPC/Networking: subprocess, socket, signal, popen2,
hasattr(object, "name") check if object has attr. if o in ("-s", "--lol"): spam = a asyncore, asynchat
hash(object) return hash for object if o in ("-h", "--help"): show_help()
id(object) Internet: webbrowser, cgi, scitb, wsgiref, urllib,
unique integer (mem address)
isinstance(object, httplib, ftplib, imaplib, nntplib, ...lib, smtpd,
check for type
uuid, urlparse, SocketServer, ...Server,, cookielib,
classOrType) 6 Input/Output Cookie, xmlrpclib
issubclass(class1, class2) class2 subclass of class1? f=codecs.open(if,"rb","utf-8") open file with encoding
iter(object, sentinel) Multimedia: audioop, imageop, aifc, sunau, wave, chunk,
return iterator for object file = open(infilename, "wb") open file without encoding
locals() colorsys, rgbimg, imghdr, sndhdr, ossaudiodev
dict of local vars of caller codecs.EncodedFile(...) wrap file into encoding
repr(object), str(object) Tk: Tkinter, Tix, ScrolledText, turtle
return string-representation r, w, a, r+ read, write, append, random
vars(object) return __dict__ rb, wb, ab, r+b Internationalization: gettext, locale
modes without eol conversion
None the NULL object file.read(N) N bytes ( entire file if no N ) Program Frameworks: cmd, shlex
if __name__ == "__main__": make modul executable file.readline() the next linestring Development: pydoc, doctest, unittest, test
file.readlines() list of linestring Runtime: sys, warnings, contextlib, atexit, traceback,
file.write(string) write string to file qc, inspect, site, user, fpectl
4 Exception Handling file.writelines(list) write list of linestrings Custom Interpreters: code, codeop
try: ... Try-block file.close() close file Restricted Execution: rexec, Bastion
except ExceptionName: catch exception file.tell() current file position Importing: imp, zipimport, pkgutil, modulefinder, runpy
except (Ex1, ...), data: multiple, with data file.seek(offset, whence) jump to file position Language: parser, symbol, token, keyword, tokenize,
print data exception handling os.truncate(size) limit output to size tabnanny, pyclbr, py_compile, compileall, dis,
raise pass up (re-raise) exception os.tmpfile() open anon temporary file pickletools, distutils
else: ... if no exception occurred pickle.dump(x, file) make object persistent Windows: msilib, msvcrt, _winreq, winsound
finally: ... in any case x = pickle.load(file) load object from file Misc: formatter