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


Open a file in a specific encoding:

f ="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,

Replace a pattern in a string:

def foo(matchobj):
    word =
    # ...
    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:],
                           ["extension", "directory", "output"])

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