Sunteți pe pagina 1din 3

VISIT…

Python 2.5 Reference Card 1.3 Dictionaries (Mappings) padding: center(w,c), ljust(w,c), lstrip(cs),
d={'x':42, 'y':3.14, 'z':7} dict creation rjust(w,c), rstrip(cs), strip(cs), zfill(w),
(c) 2009 Michael Goerz <goerz@physik.fu-berlin.de>
http://www.physik.fu-berlin.de/~goerz/ d['x'] get entry for 'x' expandtabs(ts)
This work is licensed under the Creative Commons Attribution-Noncommercial-Share Alike 3.0 License. len(d) number of keys checking: isalnum, isalpha, isdigit, islower, isspace,
To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/ 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,
printable, punctuation, uppercase, whitespace
1.1 Numbers d.items() list of all items
42 052 0x2A 42L 052L 0x2AL d.keys() list of all keys Regexes: import re
42 (dec, oct, hex, short/long)
d.values() list of all values r=re.compile(r'rx',re.ILMSUX) comile 'rx' as regex
0.2 .8 4. 1.e10 1.0e-7 floating point value
i=d.iteritems(); i.next() iterator over items (?P<id>...) named group
z = 5.0 – 2.0J; complex number
i=d.iterkeys(); i.next() iterator over keys m=r.match(s,b,e) full match
z = complex(real, imag) complex number
i=d.itervalues(); i.next() iterator over values re.match(r'(?iLmsux)rx',s) direct regex usage
z.real; z.imag real and imag part of z
d.get(k,x) get entry for k, or return x m=r.search(s,b,e) partial match
True; False constants for boolean values
d.clear() remove all items l=r.split(s,ms) split and return list
abs(n) absolute value of n
d.setdefault(k,x) return d[k] or set d[k]=x l=r.findall(string) list of all matched groups
divmod(x, y) (x/y, x%y)
hex(n) d.popitem() return and delete an item s=r.sub(s,r,c) replace c counts of s with r
create hex string
oct(n) 1.4 Sets (s,n)=r.subn(s,r,c) n is number of replacements
create octal string
ord(c) s=re.escape(s) escape all non-alphanumerics
unicode code point of char s=set(s); fs=frozenset(s) create set
round(x,n) m.start(g);m.span(g);m.end(g) group-match delimiters
round x to n decimal places fs.issubset(t); s<=t all s in t?
cmp(x,y) m.expand(s) replace \1 etc. with matches
x<y: -1, x==y: 0, x>y: 1 fs.issuperset(t); s>=t all t in s?
m.group(g); m.group("name") matched group no. g
coerce(x, y) (x,y), make same type fs.union(t); s|t all elements from s and t m.groups() list of groups
pow(x,y,z) (x**y) % z fs.intersection(t); s&t elements both in s and t m.groupdict() dict of named groups
float("3.14") float from string 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) 1.5 Strings and Regular Expressions for target in iter: statements for loop
s[-2][-1] get list element (1.4) else: statements
"bla"; 'hello "world"' string (of bytes)
s1+s1 sequence concat for key,value in d.items():... multiple identifiers
"""bla""", '''bla''' triple quotes for multiline
n*s1 repeat s1 n times break, continue end loop / jump to next
\ \\ \0 cont., backslash, null char
s[i:j]; s[i:]; s[:j] slicing (i incl., j excl.) \N{id} \uhhhh \Uhhhhhhhh print "hello world", print without newline
unicode char
s[i:j:k] slice with stride k \xhh \ooo hex, octal byte [ expr for x in seq lc ] list comprehension
s[::2]; s[::-1] every 2nd Element / reverse s u"Ünic\u00F8de"; u"\xF8" unicode string (of characters) lc = for x in seq / if expr with lc-clauses
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 mimetools, mimetypes, MimeWriter, mimify, multifile,
shutil module: copy, copy2, copyfile, copyfileobj,
Super.__init__(self) call superclass constructor rfc822, base64, binhex, binascii, quopri, uu
copymode, copystat, copytree, rmtree
self.member = x per-instance data os.path module: abspath, altsep, basename, commonprefix, Structured Markup Processing Tools: HTMLParser, sgmllib,
def __del__(self): ... destructor htmllib, htmlentitydefs, xml.parsers.expat, xml.dom.*,
curdir, defpath, dirname, exists, expanduser,
__str__, __len__, __cmp__,__ some operator overloaders expandvar, extsep, get[acm]time, getsize, isabs, xml.sax.*, xml.etree.ElementTree
__iter__(self): return self use next method for iterator isdir, isfile, islink, ismout, join, lexists, File Formats: csv, ConfigParser, robotparser, netrc,
__call__ call interceptor normcase, normpath, pardir, pathsep, realpath, xdrlib
__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) Internet: webbrowser, cgi, scitb, wsgiref, urllib,
isinstance(object, 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 Multimedia: audioop, imageop, aifc, sunau, wave, chunk,
locals() dict of local vars of caller codecs.EncodedFile(...) wrap file into encoding colorsys, rgbimg, imghdr, sndhdr, ossaudiodev
repr(object), str(object) 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 Internationalization: gettext, locale
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
assert expression debug assertion

S-ar putea să vă placă și