Fork me on GitHub

Python Cheat Sheet

List comprehension

[foo if blah else bar for i in range(...)]

Join a list of strings

", ".join(my_list)

Decode a string in a specific encoding

my_str.decode("iso8859-1")

Open a file in a specific encoding:

f = codecs.open("foo.txt", "r", "iso8859-1")

Filter a dictionary

dict((k, v) for k, v in hash.iteritems() if len(v) != 1)

Create a regex of punctuation:

import string

special_chars = ["?", "|", "$", "+", "^", "[", "]", "{", "}", "(", ")", "*"]
punctuation = "|".join(
map(lambda c: "\\" + c if (c in special_chars) else c,
    list(string.punctuation)))

Replace a pattern in a string:

def foo(matchobj):
    word = matchobj.group(0)
    # ...
    return word
# ...
line = re.sub(r"(\w+)", foo, line)

Parse command line arguments:

import getopt
import sys

extension = None
directory = "."

opts, args = getopt.getopt(sys.argv[1:],
                           "e:d:o:",
                           ["extension", "directory", "output"])

for opt, arg in opts:
    if opt in ("-e", "--extension"):
        extension = arg
    if opt in ("-d", "--directory"):
        directory = arg
Tags: python