Show Menu
Cheatography

Essential Python Cheat Sheet by

A brief Python language reference for Python 2.6+ / 3.0+.

Data Types

Integer
-256, 15
Float
-253.23, 1.253e-10
String
"­Hel­lo", 'Goodbye', "­"­"­Mul­til­ine­"­"­"
Boolean
True, False
List
[ value, ... ]
Tuple
( value, ... )1
Dictionary
{ key: value, ... }
Set
{ value, value, ... }2
1 Parent­heses usually optional
2 Create an empty set with set()

Statements

If Statement
if expression:
 ­ ­sta­tements
elif expression:
 ­ ­sta­tements
else:
 ­ ­sta­tements

While Loop
while expression:
 ­ ­sta­tements

For Loop
for var in collection:
 ­ ­sta­tements

Counting For Loop
for i in range(start, end [, step]):
 ­ ­sta­tements
(start is included; end is not)

Arithmetic Operators

x + y
add
x - y
subtract
x * y
multiply
x / y
divide
x % y
modulus
x ** y
xy
Assignment shortcuts: x op= y
Example: x += 1 increments x

Comparison Operators

x< y
Less
x <= y
Less or eq
x > y
Greater
x >= y
Greater or eq
x == y
Equal
x != y
Not equal

Boolean Operators

not x
x and y
x or y

Exception Handling

try:
 ­ ­sta­tements
except [ exception type [ as var ] ]:
 ­ ­sta­tements
finally:
 ­ ­sta­tements
 

Conversion Functions

int(expr)
Converts expr to integer
float(expr)
Converts expr to float
str(expr)
Converts expr to string
chr(num)
ASCII char num

String / List / Tuple Operations

len(s)
length of s
s[i]
ith item in s (0-based)
s[start : end]
slice of s from start (included) to end (excluded)
x in s
True if x is contained in s
x not in s
True if x is not contained in s
s + t
the concat­enation of s with t
s * n
n copies of s concat­enated
sorted(s)
a sorted copy of s
s.index(item)
position in s of item

More String Operations

s.lower()
lowercase copy of s
s.replace(old, new)
copy of s with old replaced with new
s.split( delim )
list of substrings delimited by delim
s.strip()
copy of s with whitespace trimmed
s.upper()
uppercase copy of s

Mutating List Operations

del lst[i]
Deletes ith item from lst
lst.append(e)
Appends e to lst
lst.insert(i, e)
Inserts e before ith item in lst
lst.sort()
Sorts lst

Dictionary Operations

len(d)
Number of items in d
del d[key]
Removes key from d
key in d
True if d contains key
d.keys()
Returns a list of keys in d

Function Defini­tions

def name(arg1, arg2, ...):
 ­ statements
 ­ ­return expr
 

Enviro­nment

sys.argv
List of command line arguments (argv[0] is execut­able)
os.environ
Dictionary of enviro­nment variables
os.curdir
String with path of current directory
import sys; print(­sys.ar­gv)­ ­ ­ ­ or
from sys import argv; print(­argv)

String Formatting

"­Hello, {0} {1}".fo­rma­t("a­be", "­jon­es")
Hello, abe jones

"­Hello, {fn} {ln}".f­orm­at(­fn=­"­abe­", ln="­jon­es")
Hello, abe jones

"You owe me ${0:,.2­f}­".fo­rma­t(2­534­22.3)
You owe me $253,4­22.30

now = dateti­me.n­ow()
'{:%Y-­%m-%d %H:%M:­%S}­'.f­orm­at(now)
2012-05-16 15:04:33

Useful Functions

exit( code )
Terminate program with exit code
raw_in­put­("prompt")
Print prompt and readline() from stdin1
1 Use input(­"prompt") in Python 3

Code Snippets

Loop Over Sequence
for index, value in enumer­ate­(seq):
 ­ ­pri­nt(­"{} : {}".f­or­mat­(index, value))

Loop Over Dictionary
for key in sorted­(dict):
 ­ ­pri­nt(­dic­t[key])

Read a File
with open("f­ile­nam­e", "­r") as f:
 ­ for line in f:
 ­ ­ ­ line = line.r­str­ip(­"­\n") # Strip newline
 ­ ­ ­ ­pri­nt(­line)

Other References

                       
 

Comments

Amazing cheatsheet.

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          More Cheat Sheets by sschaub