Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
188 views

Python Refcard

The document provides a summary of Python's built-in data types and common programming concepts in 3 sentences or less: It lists Python's basic data types including numbers, strings, lists, dictionaries, sets, and regular expressions. It also covers common programming concepts like functions, classes, exceptions, modules and input/output. The document serves as a quick reference for Python syntax and standard library functions related to variables, sequences, strings, regular expressions, exceptions, modules and file I/O.

Uploaded by

morbosus
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
188 views

Python Refcard

The document provides a summary of Python's built-in data types and common programming concepts in 3 sentences or less: It lists Python's basic data types including numbers, strings, lists, dictionaries, sets, and regular expressions. It also covers common programming concepts like functions, classes, exceptions, modules and input/output. The document serves as a quick reference for Python syntax and standard library functions related to variables, sequences, strings, regular expressions, exceptions, modules and file I/O.

Uploaded by

morbosus
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Python 2.

5 Reference Card

string (of bytes) triple quotes for (c) 2007 Michael Goerz <goerz@physik.fu-berlin.de> l.index(x) multiline http://www.physik.fu-berlin.de/~goerz/ l.append(x) \ \\ \0 cont., backslash, null Information taken liberally from the python documentation and various other sources. x=l.pop() char You may freely modify and distribute this document. l.extend(l2) \N{id} \uhhhh \Uhhhhhhhh unicode char l.insert(i,x) \xhh \ooo hex, octal byte 1 Variable Types l.remove(x) u"nic\u00F8de"; u"\xF8" unicode string (of l.reverse() characters) 1.1 Numbers l.sort(f) r"C:\new\text.dat"; ur"\\" raw string (unicode) 42 052 0x2A 42L 052L 0x2AL 42 (dec, oct, hex, str(3.14); str(42) string conversion short/long) zip(s,t,...) "%s-%s-%s" % (42,3.14,[1,2,3]) string substitution 0.2 .8 4. 1.e10 1.0e-7 floating point value '\t'.join(seq) join sequences with 1.3 Dictionaries (Mappings) z = 5.0 2.0J; complex number separator d={'x':42, 'y':3.14, 'z':7} dict creation z = complex(real, imag) complex number s.decode('utf-8') latin-1 string to unicode d['x'] get entry for 'x' z.real; z.imag real and imag part of z string len(d) number of keys True; False constants for boolean u.encode('utf-8') unicode string to utf-8 del(d['x']) delete entry from dict values string d.copy() create shallow copy abs(n) absolute value of n chr(i), unichr(i) char from code point d.has_key(k) does key exist? divmod(x, y) (x/y, x%y) str(x) string from d.items() list of all items hex(n) create hex string number/object d.keys() list of all keys oct(n) create octal string Other String Methods: d.values() list of all values ord(c) unicode code point of search and replace: find(s,b,e), rfind(s,b,e), i=d.iteritems(); i.next() iterator over items char index(s,b,e), rindex(s,b,e), count(s,b,e), i=d.iterkeys(); i.next() iterator over keys round(x,n) round x to n decimal endswith(s,b,e), startswith(s,b,e), replace(o,n,m) i=d.itervalues(); i.next() iterator over values places get entry for k, or return formatting: capitalize, lower, upper, swapcase, title cmp(x,y) x<y: -1, x==y: 0, x>y: 1 d.get(k,x) splitting: partition(s), rpartition(s), split(s,m), x coerce(x, y) (x,y), make same type rsplit(s,m), splitlines(ke) d.clear() remove all items pow(x,y,z) (x**y) % z d.setdefault(k,x) return d[k] or set d[k]=x padding: center(w,c), ljust(w,c), lstrip(cs), float("3.14") float from string rjust(w,c), rstrip(cs), strip(cs), zfill(w), d.popitem() return and delete an int("42", base) int from string expandtabs(ts) item import math; import cmath more math functions checking: isalnum, isalpha, isdigit, islower, isspace, import random; random number 1.4 Sets istitle, isupper generators s=set(s); fs=frozenset(s) create set String Constants: import string 1.2 Sequences (lists are mutable, tuples and strings are fs.issubset(t); s<=t all s in t? digits, hexdigits, letters, lowercase, octdigits, fs.issuperset(t); s>=t all t in s? immutable) printable, punctuation, uppercase, whitespace fs.union(t); s|t all elements from s and s=l=[1, "bla", [1+2J, 1.4], 4] list creation Regexes: import re t s=t=(1, "bla", [1+2J, 1.4], 4) tuple creation r=re.compile(r'rx',re.ILMSUX) comile 'rx' as regex fs.intersection(t); s&t elements both in s and l=list(t); t=tuple(l) list/tuple conversion (?P<id>...) named group t l=range(1000) list of integers (0-999) m=r.match(s,b,e) full match fs.difference(t); s-t all s not in t s=xrange(1000) immut. xrangere.match(r'(?iLmsux)rx',s) direct regex usage fs.symmetric_difference(t);s^t all either s or t sequence m=r.search(s,b,e) partial match fs.copy() shallow copy of s iteratorfromsequence i=iter(s); i.next() l=r.split(s,ms) split and return list s.update(t); s|=t add elements of t s[2][0] get list element (1+2J) l=r.findall(string) list of all matched s.intersection_update(t); s&=t keep only what is also s[-2][-1] getlistelement(1.4) groups in t s1+s1 sequence concat s=r.sub(s,r,c) replace c counts of s s.difference_update(t); s-=t remove elements of t n*s1 repeat s1 n times with r s.symmetric_differ...(t); s^=t keep only symm. s[i:j]; s[i:]; s[:j] slicing (i incl., j excl.) (s,n)=r.subn(s,r,c) n is number of difference s[i:j:k] slice with stride k replacements s.add(x) add x to fs s[::2]; s[::-1] every 2nd Element / s=re.escape(s) escape all nons.remove(x); fs.discard(x); remove x (/ with reverse s alphanumerics exception) x in s; x not in s is x a member of s? m.start(g);m.span(g);m.end(g) group-match delimiters s.pop(); return and remove any len(s) number of elements m.expand(s) replace \1 etc. with elem. min(s); max(s) min/max matches s.clear(); remove all elements l[i:j]=['a','b','c','d'] replace slice m.group(g); m.group("name") matched group no. g l[i:i]=['a','b'] insert before position i 1.5 Strings and Regular Expressions m.groups() list of groups

l.count(x)

number of occurances of x first index of x, or error append x at end of l pop off last element append l2 at end of l instert x at pos. i delete first x reverse l sort using f (default f =cmp) [(s[0],t[0],...),..]

"bla"; 'hello "world"' """bla""", '''bla'''

class definition shared class data methods 2 Basic Syntax constructor call superclass if expr: statements conditional constructor elif expr: statements per-instance data else: statements destructor if a is b : ... object identity __str__, __len__, __cmp__,__ some operator if a == 1 value identity overloaders while expr: statements while loop use next method for else: statements run else on normal exit __iter__(self): return self iterator while True: ... if cond: break do... while equivalent __call__ call interceptor for target in iter: statements for loop __dict__ instance-attribute else: statements dictionary for key,value in d.items():... multiple identifiers get an unknown break, continue end loop / jump to next __getattr__(self, name), attribute print "hello world", print without newline __setattr__(self, name, value) set any attribute [ expr for x in seq lc ] list comprehension callable(object) 1 if callable, 0 otherwise lc = for x in seq / if expr with lc-clauses delattr(object, "name") delete name-attr. from pass empty statement object def f(params): statements function definition del(object) unreference object/var def f(x, y=0): return x+y optional parameter dir(object) list of attr. assoc. with def f(*a1, **a2): statements additional list of object unnamed, dict of named getattr(object, "name", def) get name-attr. from paramters object def f(): f.variable = 1 ... function attribute hasattr(object, "name") check if object has attr. return expression return from function hash(object) return hash for object yield expression make function a id(object) unique integer (mem generator address) f(1,1), f(2), f(y=3, x=4) function calls isinstance(object, check for type global v bind to global variable classOrType) def make_adder_2(a): closure issubclass(class1, class2) class2 subclass of def add(b): return a+b class1? return add iter(object, sentinel) return iterator for object lambda x: x+a lambda expression dict of local vars of compile(string,filename,kind) compile string into code locals() caller object repr(object), str(object) return stringeval(expr,globals,locals) evaluate expression representation exec code in gldict, lcdict compile and execute vars(object) return __dict__ code None the NULL object execfile(file,globals,locals) execute file if __name__ == "__main__": make modul executable raw_input(prompt) input from stdin input(prompt) input and evaluate

m.groupdict()

dict of named groups

class name (superclass,...): data = value def method(self,...): ... def __init__(self, x): Super.__init__(self) self.member = x def __del__(self): ...

5 System Interaction
module search path operating system standard input/output/error sys.argv[1:] command line parameters os.system(cmd) system call os.startfile(f) open file with assoc. program os.popen(cmd, r|w, bufsize) open pipe (file object) os.popen2(cmd, bufsize, b|t) (stdin, stdout) fileobjects os.popen3(cmd, bufsize, b|t) (stdin, stdout,stderr) os.environ['VAR']; os.putenv[] read/write environment vars glob.glob('*.txt') wildcard search Filesystem Operations os module: access, chdir, chmod, chroot, getcwd, getenv, listdir, mkdir, remove, unlink, removedirs, rename, rmdir, pipe, ... shutil module: copy, copy2, copyfile, copyfileobj, copymode, copystat, copytree, rmtree os.path module: abspath, altsep, basename, commonprefix, curdir, defpath, dirname, exists, expanduser, expandvar, extsep, get[acm]time, getsize, isabs, isdir, isfile, islink, ismout, join, lexists, normcase, normpath, pardir, pathsep, realpath, samefile, sameopenfile, samestat, sep, split, splitdrive, splitext, stat, walk command line argument parsing: restlist, opts = \ getopt.getopt(sys.argv[l:],\ "s:oh",\ ["spam=", "other", "help"]) for o, a in opts: if o in ("-s", "--lol"): spam = a if o in ("-h", "--help"): show_help() sys.path sys.platform sys.stdout, stdin, stderr

6 Input/Output

f=codecs.open(if,"rb","utf-8") open file with encoding file = open(infilename, "wb") open file without 4 Exception Handling encoding 3 Object Orientation and Modules try: ... Try-block codecs.EncodedFile(...) wrap file into encoding except ExceptionName: catch exception r, w, a, r+ read, write, append, import module as alias import module except (Ex1, ...), data: multiple, with data random from module import name1,name2 load attr. into own print data exception handling rb, wb, ab, r+b modes without eol namespace raise pass up (re-raise) conversion from __future__ import * activate all new features else: ... exception file.read(N) N bytes ( entire file if no reload module reinitialize module finally: ... if no exception occurred N) module.__all__ exported attributes in any case file.readline() the next linestring module.__name__ module name / assert expression debug assertion file.readlines() list of linestring "__main__" class MyExcept(Exception): ... define user exception file.write(string) write string to file module.__dict__ module namespace raise user exception file.writelines(list) write list of linestrings __import__("name",glb,loc,fl) import module by name raise MyExcept , data

file.close() file.tell() file.seek(offset, whence) os.truncate(size) os.tmpfile() pickle.dump(x, file) x = pickle.load(file)

7 Standard Library (almost complete)


String Services: string, re, struct, difflib, StringIO, cStringIO, textwrap, codecs, unicodedata, stringprep, fpformat File/Directory Access: os.path, fileinput, stat, statvfs, filecmp, tempfile, glob, fnmatch, linecache, shutil, dircache Generic OS services: os, time, optparse, getopt, logging, getpass, curses, platform, errno, ctypes Optional OS services: select, thread, threading, dummy_thread, dummy_threading, mmap, readline, rlcompleter Data Types: datetime, calendar, collections, heapq, bisect, array, sets, sched, mutex, Queue, weakref, UserDict, UserList, UserString, types, new, copy, pprint, repr Numeric and Math Modules: math, cmath, decimal, random, itertools, functools, operator Internet Data Handling: email, mailcap, mailbox, mhlib, mimetools, mimetypes, MimeWriter, mimify, multifile, rfc822, base64, binhex, binascii, quopri, uu Structured Markup Processing Tools: HTMLParser, sgmllib, htmllib, htmlentitydefs, xml.parsers.expat, xml.dom.*, xml.sax.*, xml.etree.ElementTree File Formats: csv, ConfigParser, robotparser, netrc, xdrlib Crypto Services: hashlib, hmac, md5, sha Compression: zlib, gzip, bz2, zipfile, tarfile Persistence: pickle, cPickle, copy_reg, shelve, marshal, anydbm, whichdb, dbm, gdbm, dbhash, bsddb, dumbdbm, sqlite3 Unix specific: posix, pwd, spwd, grp, crypt, dl, termios, tty, pty, fcntl, posixfile, resource, nis, syslog, commands IPC/Networking: subprocess, socket, signal, popen2, asyncore, asynchat Internet: webbrowser, cgi, scitb, wsgiref, urllib, httplib, ftplib, imaplib, nntplib, ...lib, smtpd, uuid, urlparse, SocketServer, ...Server,, cookielib, Cookie, xmlrpclib Multimedia: audioop, imageop, aifc, sunau, wave, chunk, colorsys, rgbimg, imghdr, sndhdr, ossaudiodev Tk: Tkinter, Tix, ScrolledText, turtle Internationalization: gettext, locale Program Frameworks: cmd, shlex Development: pydoc, doctest, unittest, test Runtime: sys, warnings, contextlib, atexit, traceback, qc, inspect, site, user, fpectl

close file current file position jump to file position limit output to size open anon temporary file make object persistent load object from file

Custom Interpreters: code, codeop Restricted Execution: rexec, Bastion Importing: imp, zipimport, pkgutil, modulefinder, runpy Language: parser, symbol, token, keyword, tokenize, tabnanny, pyclbr, py_compile, compileall, dis, pickletools, distutils Windows: msilib, msvcrt, _winreq, winsound Misc: formatter

You might also like