P. 1


|Views: 52|Likes:
Published by soft003

More info:

Published by: soft003 on Feb 28, 2011
Copyright:Attribution Non-commercial


Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less





Python 2.

5 Reference Card
(c) 2009 Michael Goerz <goerz@physik.fu-berlin.de> http://www.physik.fu-berlin.de/~goerz/ This work is licensed under the Creative Commons Attribution-Noncommercial-Share Alike 3.0 License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/

1.3 Dictionaries (Mappings)
d={'x':42, 'y':3.14, 'z':7} d['x'] len(d) del(d['x']) d.copy() d.has_key(k) d.items() d.keys() d.values() i=d.iteritems(); i.next() i=d.iterkeys(); i.next() i=d.itervalues(); i.next() d.get(k,x) d.clear() d.setdefault(k,x) d.popitem() dict creation get entry for 'x' number of keys delete entry from dict create shallow copy does key exist? list of all items list of all keys list of all values iterator over items iterator over keys iterator over values get entry for k, or return x remove all items return d[k] or set d[k]=x return and delete an item create set all s in t? all t in s? all elements from s and t elements both in s and t all s not in t all either s or t shallow copy of s add elements of t keep only what is also in t remove elements of t keep only symm. difference add x to fs remove x (/ with exception) return and remove any elem. remove all elements

1 Variable Types
1.1 Numbers
42 052 0x2A 42L 052L 0x2AL 42 (dec, oct, hex, short/long) 0.2 .8 4. 1.e10 1.0e-7 floating point value z = 5.0 – 2.0J; complex number z = complex(real, imag) complex number z.real; z.imag real and imag part of z True; False constants for boolean values abs(n) absolute value of n divmod(x, y) (x/y, x%y) hex(n) create hex string oct(n) create octal string ord(c) unicode code point of char round(x,n) round x to n decimal places cmp(x,y) x<y: -1, x==y: 0, x>y: 1 coerce(x, y) (x,y), make same type pow(x,y,z) (x**y) % z float("3.14") float from string int("42", base) int from string import math; import cmath more math functions import random; random number generators 1.2 Sequences (lists are mutable, tuples and strings are immutable) s=l=[1, "bla", [1+2J, 1.4], 4] list creation s=t=(1, "bla", [1+2J, 1.4], 4) tuple creation l=list(t); t=tuple(l) list/tuple conversion l=range(1000) list of integers (0-999) s=xrange(1000) immut. xrange-sequence i=iter(s); i.next() iterator from sequence s[2][0] get list element (1+2J) s[-2][-1] get list element (1.4) s1+s1 sequence concat n*s1 repeat s1 n times s[i:j]; s[i:]; s[:j] slicing (i incl., j excl.) s[i:j:k] slice with stride k s[::2]; s[::-1] every 2nd Element / reverse s x in s; x not in s is x a member of s? len(s) number of elements min(s); max(s) min/max l[i:j]=['a','b','c','d'] replace slice l[i:i]=['a','b'] insert before position i l.count(x) number of occurances of x l.index(x) first index of x, or error l.append(x) append x at end of l x=l.pop() pop off last element l.extend(l2) append l2 at end of l l.insert(i,x) instert x at pos. i l.remove(x) delete first x l.reverse() reverse l l.sort(f) sort using f (default f =cmp) zip(s,t,...) [(s[0],t[0],...),..]

1.4 Sets
s=set(s); fs=frozenset(s) fs.issubset(t); s<=t fs.issuperset(t); s>=t fs.union(t); s|t fs.intersection(t); s&t fs.difference(t); s-t fs.symmetric_difference(t);s^t fs.copy() s.update(t); s|=t s.intersection_update(t); s&=t s.difference_update(t); s-=t s.symmetric_differ...(t); s^=t s.add(x) s.remove(x); fs.discard(x); s.pop(); s.clear();

padding: center(w,c), ljust(w,c), lstrip(cs), rjust(w,c), rstrip(cs), strip(cs), zfill(w), expandtabs(ts) checking: isalnum, isalpha, isdigit, islower, isspace, istitle, isupper String Constants: import string digits, hexdigits, letters, lowercase, octdigits, printable, punctuation, uppercase, whitespace Regexes: import re r=re.compile(r'rx',re.ILMSUX) comile 'rx' as regex (?P<id>...) named group m=r.match(s,b,e) full match re.match(r'(?iLmsux)rx',s) direct regex usage m=r.search(s,b,e) partial match l=r.split(s,ms) split and return list l=r.findall(string) list of all matched groups s=r.sub(s,r,c) replace c counts of s with r (s,n)=r.subn(s,r,c) n is number of replacements s=re.escape(s) escape all non-alphanumerics m.start(g);m.span(g);m.end(g) group-match delimiters m.expand(s) replace \1 etc. with matches m.group(g); m.group("name") matched group no. g m.groups() list of groups m.groupdict() dict of named groups

2 Basic Syntax
if expr: statements elif expr: statements else: statements if a is b : ... if a == 1 while expr: statements else: statements while True: ... if cond: break for target in iter: statements else: statements for key,value in d.items():... break, continue print "hello world", [ expr for x in seq lc ] lc = for x in seq / if expr pass def f(params): statements def f(x, y=0): return x+y def f(*a1, **a2): statements def f(): f.variable = 1 ... return expression yield expression f(1,1), f(2), f(y=3, x=4) global v def make_adder_2(a): def add(b): return a+b return add lambda x: x+a compile(string,filename,kind) conditional object identity value identity while loop run else on normal exit do... while equivalent for loop multiple identifiers end loop / jump to next print without newline list comprehension with lc-clauses empty statement function definition optional parameter additional list of unnamed, dict of named paramters function attribute return from function make function a generator function calls bind to global variable closure lambda expression compile string into code object

1.5 Strings and Regular Expressions
"bla"; 'hello "world"' string (of bytes) """bla""", '''bla''' triple quotes for multiline \ \\ \0 cont., backslash, null char \N{id} \uhhhh \Uhhhhhhhh unicode char \xhh \ooo hex, octal byte u"Ünic\u00F8de"; u"\xF8" unicode string (of characters) r"C:\new\text.dat"; ur"\\Ü" raw string (unicode) str(3.14); str(42) string conversion "%s-%s-%s" % (42,3.14,[1,2,3]) string formatting '\t'.join(seq) join sequences with separator s.decode('utf-8') latin-1 string to unicode string u.encode('utf-8') unicode string to utf-8 string chr(i), unichr(i) char from code point str(x) string from number/object Other String Methods: search and replace: find(s,b,e), rfind(s,b,e), index(s,b,e), rindex(s,b,e), count(s,b,e), endswith(s,b,e), startswith(s,b,e), replace(o,n,m) formatting: capitalize, lower, upper, swapcase, title splitting: partition(s), rpartition(s), split(s,m), rsplit(s,m), splitlines(ke)

close() close file Restricted Execution: rexec. statvfs. winsound else: . sched. dis. readline. split. pwd. sameopenfile. inspect. dbm. hmac. Super. shutil.sax. urlparse. site. pkgutil.read(N) N bytes ( entire file if no N ) Program Frameworks: cmd. cmath. unicodedata.txt') wildcard search __import__("name". isfile. getenv. ismout.__dict__ module namespace UserDict. basename. msvcrt."rb".getopt(sys. xml.load(file) load object from file Misc: formatter finally: .): . SocketServer. whichdb.environ['VAR']..ElementTree some operator overloaders expandvar. imaplib.. "name". bsddb. re. program Optional OS services: select. __cmp__. append. linecache. __str__. _winreq. Try-block file.. collections."utf-8") open file with encoding Cookie. open file without encoding iter(object. r+b modes without eol conversion Internationalization: gettext. assoc. bufsize. new.. glob.. removedirs. traceback. stdout) fileobjects rlcompleter module. heapq.glob('*. ossaudiodev wrap file into encoding locals() dict of local vars of caller r. whence) jump to file position Language: parser. xml. pardir. stat. token. UserList. . locale vars(object) return __dict__ file. cStringIO. def __init__(self.) colorsys. module search path filecmp. pty. stderr standard input/output/error 3 Object Orientation and Modules Generic OS services: os. unlink. functools. .. dummy_threading.dom.startfile(f) open file with assoc.write(string) write string to file qc. nis. os. sha instance-attribute dictionary samefile. glob. cPickle. mailcap. StringIO. print data exception handling os. mmap. curdir. difflib. user. resource. mimetypes.member = x per-instance data os. Queue. module. x): constructor mimetools... "help"]) commands getattr(object. netrc. "--help"): show_help() Internet: webbrowser. r+ read. marshal. cookielib. splitext. rmdir. tarfile get an unknown attribute splitdrive. in any case assert expression debug assertion eval(expr. bz2. samestat. from object for o. sys. mailbox. base64. File Formats: csv.popen(cmd. file. uu copymode. mkdir. "name") IPC/Networking: subprocess.. 1 if callable.). rmtree self. gzip. runpy except ExceptionName: catch exception file. logging. chmod.. operator def method(self. chunk.__init__(self) call superclass constructor rfc822. ctypes os. weakref.platform operating system dircache sys. command line argument parsing: callable(object) anydbm. copy2.popen2(cmd. pathsep. unreference object/var "s:oh". dbhash. get[acm]time. sets.argv[1:] command line parameters import module as alias import module getpass. check if object has attr. copy_reg.\ del(object) Unix specific: posix. smtpd. dirname. zipfile. fileinput. mimify. repr Filesystem Operations class name (superclass. data: multiple. MimeWriter. errno.readlines() list of linestring Runtime: sys. stdout. "name") sqlite3 delete name-attr. sunau.. ConfigParser.fl) import module by name pprint. with data os. data = value shared class data listdir.writelines(list) write list of linestrings Custom Interpreters: code. chroot. copy. pyclbr..parsers. str(object) return string-representation rb. keyword. islink. . chdir. thread. textwrap. __len__.tell() current file position Importing: imp. zipimport. ab.name2 load attr. wsgiref.path File/Directory Access: os. isinstance(object. stat. posixfile. __dict__ Crypto Services: hashlib. tokenize. value) set any attribute Persistence: pickle. b|t) (stdin.. getsize. codecs. curses. os. Structured Markup Processing Tools: HTMLParser. multifile. distutils raise pass up (re-raise) exception pickle. Numeric and Math Modules: math. copyfileobj. shelve.expat. signal. name). compileall.. copytree. module. destructor htmllib. gdbm.. methods Internet Data Handling: email. py_compile. commonprefix. contextlib. test make modul executable file. class2) class2 subclass of class1? file = open(infilename. defpath. dumbdbm. walk __setattr__(self. spwd.locals) exec code in gldict.. opts = \ delattr(object.path. fcntl.. quopri. dl.): class definition os module: access.seek(offset. from __future__ import * activate all new features dummy_thread.truncate(size) limit output to size tabnanny. a. join.path module: abspath. realpath. itertools. binascii.__name__ module name / "__main__" os.glb.Server. r|w.open(if. fpectl file.popen3(cmd. list of attr. normpath. sentinel) return iterator for object codecs. grp. doctest. threading. mutex.dump(x. "wb") Multimedia: audioop. sndhdr. pipe.. wave. isabs. lexists.. __iter__(self): return self use next method for iterator isdir. htmlentitydefs. "--lol"): spam = a asyncore. codeop 4 Exception Handling file. from object getopt. termios.. optparse. time. define user exception raise MyExcept(data) raise user exception 7 Standard Library (almost complete) . getopt.. struct. except (Ex1. urllib. robotparser.. popen2.locals) raw_input(prompt) input(prompt) evaluate expression compile and execute code execute file input from stdin input and evaluate class MyExcept(Exception): . exists.*. remove. __call__ xdrlib call interceptor normcase. b|t) (stdin. cgi. check for type 6 Input/Output uuid. shutil module: copy.system(cmd) system call from module import name1. modulefinder. atexit.String Services: string. md5. decimal. altsep.\ dir(object) tty. symbol. copyfile. id(object) unique integer (mem address) httplib.__ xml.*. ScrolledText. if o in ("-s". write. with object ["spam=". asynchat hash(object) return hash for object if o in ("-h".loc. shlex None the NULL object file. aifc. sgmllib.. xml.stderr) Data Types: datetime.EncodedFile(.. file) make object persistent Windows: msilib. xmlrpclib issubclass(class1. sys. rename. syslog. ftplib. turtle repr(object).. stringprep. bufsize) open pipe (file object) reload module reinitialize module os. calendar. bufsize. sep. 0 otherwise restlist. __getattr__(self.stdout. rgbimg. lcdict execfile(file. wb. UserString.etree. random Tk: Tkinter. a in opts: hasattr(object. array. getcwd. stdin.tmpfile() open anon temporary file pickletools.. classOrType) f=codecs. Tix. extsep. imageop.globals..readline() the next linestring if __name__ == "__main__": Development: pydoc.. crypt. into own namespace os. def __del__(self): . nntplib. binhex. random.argv[l:]. fnmatch. 5 System Interaction fpformat sys. socket. platform.putenv[] read/write environment vars bisect. imghdr. "other".lib. w.__all__ exported attributes os. name. unittest. mhlib. def) get name-attr. Bastion try: .. copystat. Compression: zlib. tempfile. scitb. types. if no exception occurred x = pickle. . expanduser.globals. warnings.

You're Reading a Free Preview

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->