Python 2v5 Reference Card

ADVERTISEMENT

Python 2.5 Reference Card
1.3 Dictionaries (Mappings)
padding: center(w,c), ljust(w,c), lstrip(cs),
rjust(w,c), rstrip(cs), strip(cs), zfill(w),
d={'x':42, 'y':3.14, 'z':7}
dict creation
(c) 2009 Michael Goerz <goerz@physik.fu-berlin.de>
expandtabs(ts)
d['x']
get entry for 'x'
checking: isalnum, isalpha, isdigit, islower, isspace,
This work is licensed under the Creative Commons Attribution-Noncommercial-Share Alike 3.0 License.
len(d)
number of keys
To view a copy of this license, visit
istitle, isupper
del(d['x'])
delete entry from dict
String Constants: import string
d.copy()
create shallow copy
1 Variable Types
digits, hexdigits, letters, lowercase, octdigits,
d.has_key(k)
does key exist?
printable, punctuation, uppercase, whitespace
1.1 Numbers
d.items()
list of all items
Regexes: import re
d.keys()
list of all keys
42 052 0x2A 42L 052L 0x2AL
42 (dec, oct, hex, short/long)
r=re.compile(r'rx',re.ILMSUX)
comile 'rx' as regex
d.values()
list of all values
0.2
.8
4.
1.e10
1.0e-7
floating point value
(?P<id>...)
named group
i=d.iteritems(); i.next()
iterator over items
z = 5.0 – 2.0J;
complex number
m=r.match(s,b,e)
full match
i=d.iterkeys(); i.next()
iterator over keys
z = complex(real, imag)
complex number
re.match(r'(?iLmsux)rx',s)
direct regex usage
i=d.itervalues(); i.next()
iterator over values
z.real; z.imag
real and imag part of z
m=r.search(s,b,e)
partial match
d.get(k,x)
get entry for k, or return x
True; False
constants for boolean values
l=r.split(s,ms)
split and return list
d.clear()
remove all items
abs(n)
absolute value of n
l=r.findall(string)
list of all matched groups
d.setdefault(k,x)
return d[k] or set d[k]=x
divmod(x, y)
(x/y, x%y)
s=r.sub(s,r,c)
replace c counts of s with r
d.popitem()
return and delete an item
hex(n)
create hex string
(s,n)=r.subn(s,r,c)
n is number of replacements
1.4 Sets
oct(n)
create octal string
s=re.escape(s)
escape all non-alphanumerics
ord(c)
unicode code point of char
s=set(s); fs=frozenset(s)
create set
m.start(g);m.span(g);m.end(g)
group-match delimiters
round(x,n)
round x to n decimal places
fs.issubset(t); s<=t
all s in t?
m.expand(s)
replace \1 etc. with matches
cmp(x,y)
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
2 Basic Syntax
fs.copy()
shallow copy of s
import random;
random number generators
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.)
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 2
nd
Element / reverse s
lc = for x in seq / if expr
with lc-clauses
u"Ünic\u00F8de"; u"\xF8"
unicode string (of characters)
x in s; x not in s
is x a member of s?
pass
empty statement
r"C:\new\text.dat"; ur"\\Ü"
raw string (unicode)
len(s)
number of elements
def f(params): statements
function definition
str(3.14); str(42)
string conversion
min(s); max(s)
min/max
def f(x, y=0): return x+y
optional parameter
"%s-%s-%s" % (42,3.14,[1,2,3]) string formatting
l[i:j]=['a','b','c','d']
replace slice
def f(*a1, **a2): statements
additional list of unnamed,
'\t'.join(seq)
join sequences with separator
l[i:i]=['a','b']
insert before position i
dict of named paramters
s.decode('utf-8')
latin-1 string to unicode string
l.count(x)
number of occurances of x
def f(): f.variable = 1 ...
function attribute
u.encode('utf-8')
unicode string to utf-8 string
return expression
return from function
l.index(x)
first index of x, or error
chr(i), unichr(i)
char from code point
yield expression
make function a generator
l.append(x)
append x at end of l
str(x)
string from number/object
f(1,1), f(2), f(y=3, x=4)
function calls
x=l.pop()
pop off last element
Other String Methods:
global v
bind to global variable
l.extend(l2)
append l2 at end of l
search and replace: find(s,b,e), rfind(s,b,e),
def make_adder_2(a):
closure
l.insert(i,x)
instert x at pos. i
index(s,b,e), rindex(s,b,e), count(s,b,e),
def add(b): return a+b
l.remove(x)
delete first x
endswith(s,b,e), startswith(s,b,e), replace(o,n,m)
return add
l.reverse()
reverse l
formatting: capitalize, lower, upper, swapcase, title
lambda x: x+a
lambda expression
l.sort(f)
sort using f (default f =cmp)
splitting: partition(s), rpartition(s), split(s,m),
compile(string,filename,kind)
compile string into code object
zip(s,t,...)
[(s[0],t[0],...),..]
rsplit(s,m), splitlines(ke)

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education
Go
Page of 2