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