Show Menu
Cheatography

Python Cheat Sheet (DRAFT) by

Python reference sheet.

This is a draft cheat sheet. It is a work in progress and is not finished yet.

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

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

Exception Handling

try:
   statements
except [ exception type [ asvar ] ]:
   statements
finally:
   statements

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
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

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.argv) or
from sys import argv; print(­argv)

Python List Methods

append(item)
pop(position)
count(item)
remove(item)
extend(list)
reverse()
index(item)
sort()
insert(position, item)

Python sys.argv

sys.ar­gv[0]
foo.py
sys.ar­gv[1]
bar
sys.ar­gv[2]
-c
sys.ar­gv[3]
qux
sys.ar­gv[4]
--h
sys.argv for the command:
$ python foo.py bar -c qux --h
 

Function Defini­tions

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

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

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()

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

Python File Methods

close()
readlines(size)
flush()
seek(offset)
fileno()
tell()
isatty()
truncate(size)
next()
write(string)
read(size)
writel­ines(list)
readline(size)

Python Indexes and Slices

len(a)
6
a[0]
h
a[5]
n
a[-1]
n
a[-2]
m
a[1:]
[i,j,k­,m,n]
a[:5]
[h,i,j­,k,m]
a[:-2]
[h,i,j,k]
a[1:3]
[i,j]
a[1:-1]
[i,j,k,m]
b=a[:]
Shallow copy of a
Indexes and Slices of a=[h,i­,j,­k,m,n]
 

Statements

If Statement
if expression:
   statements
elif expression:
   statements
else:
   statements
While Loop
while expression:
   statements
For Loop
for var in collection:
   statements
Counting For Loop
for i in range(start, end [, step]):
   statements
(start is included; end is not)

Python Date Formatting

%a
Abbrev­iated weekday (Sun)
%A
Weekday (Sunday)
%b
Abbrev­iated month name (Jan)
%B
Month name (January)
%c
Date and time
%d
Day (leading zeros) (01 to 31)
%H
24 hour (leading zeros) (00 to 23)
%I
12 hour (leading zeros) (01 to 12)
%j
Day of year (001 to 366)
%m
Month (01 to 12)
%M
Minute (00 to 59)
%p
AM or PM
%S
Second (00 to 61⁴)
%U
Week number¹ (00 to 53)
%w
Weekday² (0 to 6)
%W
Week number³ (00 to 53)
%x
Date
%X
Time
%y
Year without century (00 to 99)
%Y
Year (2008)
%Z
Time zone (GMT)
%%
A literal "­%" character (%)
¹ Sunday as start of week. All days in a new
year preceding the first Sunday are
considered to be in week 0.
² 0 is Sunday, 6 is Saturday.
³ Monday as start of week. All days in a new
year preceding the first Monday are
considered to be in week 0.
⁴ This is not a mistake. Range takes
account of leap and double­-leap seconds.

Python Datetime Methods

today()
fromor­dinal(ordinal)
now(timezo­neinfo)
combine(date, time)
utcnow()
strptime(date, format)
fromti­mes­tamp(timestamp)
utcfro­mti­mes­tamp(timestamp)

Python Class Special Methods

__new_­_(cls)
__lt__­(self, other)
__init­__(­self, args)
__le__­(self, other)
__del_­_(self)
__gt__­(self, other)
__repr­__(­self)
__ge__­(self, other)
__str_­_(self)
__eq__­(self, other)
__cmp_­_(self, other)
__ne__­(self, other)
__inde­x__­(self)
__nonz­ero­__(­self)
__hash­__(­self)
__geta­ttr­ibu­te_­_(self, name)
__seta­ttr­__(­self, name, attr)
__dela­ttr­__(­self, name)
__geta­ttr­__(­self, name)
__call­__(­self, args, kwargs)

Python Time Methods

replace()
utcoff­set()
isofor­mat()
dst()
__str__()
tzname()
strftime(format)