Python Reference Card
Python Reference Card
Basic Statements name = value! print(item)! ! ! Variable Assignment Printing Conditional String Operations len(s)! ! ! s[n]!! ! ! s[start:end] s.strip([chrs]) s.upper() s.lower() s.split([sep]) s.startswith(prefix) s.endswith(suffix) sep.join(parts) List Operations items = []! ! len(items) items[n] items[start:end] items.append(x) items.insert(n, x) items.remove(x) items.sort() for x in items: statements [expr for x in items if condition] Dictionary Operations map = { } ! ! map[key] = value v = map[key] del map[key] key in map map.keys() map.values() map.items() # # # # # # # # Empty dict Assign item Lookup item Delete item Test exists List of keys List of vals List of items # # # # # # # # # Empty list Length Indexing Slice Add to end Insert at n Remove x Sort items Iteration # # # # # # # # # # Length Indexing Slice Strip chars Case convert Case convert Split on sep Test start Test end Join parts
Reference Card
Operators x x x x x x x x x x x + y - y * y / y ** y < y <= y > y >= y == y != y ! !# Math
# Tests
Loop on condition
for x in sequence:! Iterate over data statements def func(x, y, z):! Dene a function statements return result import module! ! Library import
x in y! x not in y
# Membership
try:!! ! ! Exceptions statements except Exception as e: statements Basic Python Types None!! ! ! True, False! ! 123 !! 12.34 ! 'Hello' ! "World" ! ! ! [1, 2, 3] ! ('ACME', 50, 91.1)! {'a' : 2, 'b': 3}! Nothing Booleans Integer Float String String List Tuple Dictionary
Files # Read file all at once f = open('filename','r') data = f.read() f.close() # Read file line-by-line f = open('filename', 'r') for line in f: statements f.close() # Write to a file f = open('filename','w') f.write(text) f.close()
# List # Comprehension
Examples
Downloading Data From the Web # Python 2 import urllib u = urllib.urlopen('http://www.python.org') data = u.read() # Python 3 import urllib.request u = urllib.request.urlopen('http://www.python.org') data = u.read()