You are on page 1of 3

If you want to learn the Python programming Legalese: language, an excellent resource is Google's Python Class, which is available

at:
code.google.com/edu/languages/google-python-class/

Python Quick Reference


Based on Google's Python Class

The online content includes concise and thorough text sections with examples, exercises you can download and try out, and links to lecture videos. Once you have completed the course, you may need help remembering everything you just learned when you settle down to write your own Python programs. I know I do. That's where this quick reference comes in. The reference contains examples of each language and library feature covered in the course, along with explanatory comments. The examples are split into sections corresponding to the text in Google's class.

This work is licensed under the Creative Commons Attribution 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by/3.0/ or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA. Python and the Python logos are trademarks or registered trademarks of the Python Software Foundation, used by the author with permission from the Foundation. (Permission is automatically granted under the PSF Trademark Usage Policy for noncommercial / academic use.) The author and this work are not affiliated with or sponsored by the PSF.

by Bill Havanki Version 1.0, August 2012

The quick reference takes up two pages. You Google is a registered trademark of Google can print out the pages, trim the margins, tape Inc. The author and this work are not or glue them back-to-back, and fold them affiliated with or sponsored by Google Inc. into a single tri-fold for your desk. (If you can print double-sided, then use one piece of paper and save the tape!) Once you're ready to move beyond the material here, visit docs.python.org for the official Python documentation. Enjoy learning Python!

Introduction
a = 6

assignment; don't declare variables strings in single or double quotes len gets string, list, dict length module import first cmd line argument function, whitespace indentation, printing to stdout with newline if stmt, detect running from command line, == works on strings comment docstring, multi-line string, return string concatenation, repeating exiting

a = 'hi' a = hi len(a)

s.lower() s.upper() s.strip() s.isalpha() s.isdigit() s.isspace() s.startswith('x') s.endswith('y') s.find('z') s.replace('this', 'that') s.split(',') ','.join(l) a[1:4] a[1:] a[:4] a[:] a[-3:-1] text = '%s and %s' % ('this', 'that') u'Special character \u018e' ustr.encode('utf-8') unicode(s, 'utf-8') None 0 '' [] {} False if a and b: this() elif c or d and not e: that() else: other()

common string methods: strip trims; find returns index or -1; split returns list, default split on whitespace; join takes list

l.append(x) l.insert(idx, x) l.extend(l2) l.remove(x) l.pop(idx) l.index(x) l.sort() l.reverse() l[1:2] = ['yellow', 'orange']

common list methods: most don't return modified list; index, remove throw ValueError if missing list slices, slice assignment

import sys sys.argv[1] def foo(s): print 'Hi ', s

string slices: a[:] copies whole string printf, tuple Unicode string Unicode encode and decode false values if/elif/else, boolean operators, comparators include ==, !=, <, <=, >, >=

Sorting
sorted(l) sorted(l, reverse=True) sorted(l, key=str.lower) sorted(l, cmp=cmpFn)

sort list into new list reverse sort sort by key function sort with custom comparator (like Java) tuple; list-like indexing and len work length-1 and -0 tuples tuple assignment; works for function returns list comprehension

if __name__ == '__main__': main() # comment def foo(s): Does some stuff. return s 'Hi' + 'Hi' + 'Hi' == 'Hi' * 3 sys.exit(1)

t = (4, 2)

t1 = (4,) t0 = () (x, y, z) = (1, 2, 3)

sqs = [n * n for n in l if n >= 2]

Lists
colors = ['red', 'blue', 'green'] len(colors) == 3

Dicts and Files


list literal list length list concatenation list iteration; works on strings too test in list range generation (end is exclusive) while loop; break and continue are available
d = {} d['r'] = 'red' print d if 'r' in d: print str(d['r']) d.get('s') == None d.get('s', 'not there') == 'not there' for key in d: print key

empty dict dict key/value pair printing a dict: { 'r' : 'red' } test in dict (by key); w/o test, throws KeyError access without error access with default dict iteration by key; also d.keys(), or d.values() for iteration by value dict item access, list of tuples

Strings
a = 'hi there' a[1] == 'i' print 'The number is ' + str(pi) 1 + 2 3 * 4 / 5 % 6

characters must convert to string explicitly normal operators, // is integer division assignment operators; no ++ or -print without newline raw string

colors + ['purple'] for c in colors: print c if 'green' in colors: print 'green' range(100) == range(0, 100) while i < 100: print str(i)

A += 2 b -= 3 print 'No newline here', print r'\I \love \backslashes'

d.items() == [('r', 'red')]

for k, v in d: print k, '->', v text = %(r) % d

dict iteration by key/value pair (items()) printf substituting dict values undefining variable deleting list elements, works on slices too deleting dict entries file open, read mode, universal to cope with line endings; write and append file close loop through lines in text file (newlines remain) read all lines into list read file into one string file write alternative file write Unicode file open, produces Unicode strings; only f.write() here

emails = re.findall(r'([\w\.-] +)@([\w\.-]+)', str) match = re.search(r'o', 'foobar', re.IGNORECASE) match = re.search(r'o', lines, re.MULTILINE) re.sub(r'o', 'O', 'foobar') == 'fOObar'

find all matches, return as list of tuples by group case-insensitive search; multiline search; also re.DOTALL (. matches newline) substitution; backreferences in replacement OK

del a del l[0]

try: f = open(filename, 'rU') f.close() except IOError: sys.stderr.write('oops ', filename) import urllib ufile = urllib.ulropen(url) ufile.info() ufile.gettype() ufile.geturl() urllib.urlretrieve(url, filename) import urlparse urlparse.urljoin(burl, url)

exception handling such as IOError, ValueError; do except IOError, e: to get exception

urllib module open URL as file (can read()) get URL meta info, MIME type, base URL download URL URL construction

del d['r'] f = open('foo.txt', 'rU') f = open('bar.txt', 'w') f = open('baz.txt', 'a') f.close() for line in f: print line, lines = f.readlines() content = f.read() f.write('hi') print >> f, 'hi' import codecs f = codecs.open('foo.txt', 'rU', 'utf-8')

Utilities
import os filenames = os.listdir(dir) os.mkdir(dir) os.mkdirs(dir) os.path.join(dir, filename) os.path.abspath(path) os.path.dirname(path) os.path.basename(path) os.path.exists(path) shutil.copy(src, dest) import commands

OS module list files in directory, no . or .. make directory; intermediates too make path from file and parent directory get absolute path get directory name or filename from path path existence check copy a file commands module run a command; stdout and stderr combined run a command without status run a command, dump output to stdout

Notes

Regular Expressions
import re match = re.search(r'o', 'foobar')

regex search: returns match object or None if no match; prefer raw strings for patterns retrieving regex match retrieving regex group matches find all matches, return as list (try f.read() for str)

(status, output) = commands.getstatusoutput (cmd) output = commands.getoutput(cmd) status = os.system(cmd)

For more: code.google.com/edu/languages/google-python-class/ docs.python.org/

if match: print 'found', match.group() if match: print 'group 1 is ', match.group(1) emails = re.findall(r'[\w\.-] +@[\w\.-]+', str)

Python Quick Reference Based on Google's Python Class


by Bill Havanki http://www.linkedin.com/in/billhavanki

You might also like