Essential Python Cheat Sheet
by sschaub via cheatography.com/1000/cs/374/
Data Types Comparison Operators More String Operations (cont)
Integer -256, 15 x< y Less x <= y Less or eq s.strip() copy of s with whitespace trimmed
Float -253.23, 1.253e-10 x>y Greater x >= y Greater or eq s.upper() uppercase copy of s
String "Hello", 'Goodbye', """Multiline""" x == y Equal x != y Not equal See also
Boolean True, False http://docs.python.org/library/stdtypes.html#string-
Boolean Operators methods
List [ value, ... ]
Tuple ( value, ... )1 not x x and y x or y
Mutating List Operations
Dictionary { key: value, ... }
Exception Handling del lst[i] Deletes ith item from lst
Set { value, value, ... }2
try: lst.append( e) Appends e to lst
1 Parentheses usually optional
statements lst.insert(i, e) Inserts e before ith item in lst
2 Create an empty set with set()
except [ exception type [ as var ] ]:
lst.sort() Sorts lst
statements
Statements finally: See also
statements http://docs.python.org/library/stdtypes.html#typess
If Statement eq-mutable
if expression:
Conversion Functions
statements Dictionary Operations
elif expression: int(expr) Converts expr to integer
statements len(d) Number of items in d
float( expr) Converts expr to float
else: del d[key] Removes key from d
str(expr) Converts expr to string
statements
key in d True if d contains key
While Loop chr(num) ASCII char num
while expression: d.keys() Returns a list of keys in d
statements String / List / Tuple Operations See also
For Loop http://docs.python.org/library/stdtypes.html#mappi
len(s) length of s
for var in collection: ng-types-dict
statements s[i] ith item in s (0-based)
Counting For Loop s[start : slice of s from start (included) to Function Definitions
for i in range(start, end [, step]): end] end (excluded)
statements def name( arg1, arg2, ...):
x in s True if x is contained in s
s ta
tem
ents
(start is included; end is not)
x not in s True if x is not contained in s return expr
Arithmetic Operators s+t the concatenation of s with t
Environment
s *n n copies of s concatenated
x+y add x-y subtract
sys.argv List of command line arguments
x*y multiply x/y divide sorted(s a sorted copy of s
) (argv[0] is executable)
x%y modulus x ** y xy
os.environ Dictionary of environment
s.index( position in s of item
Assignment shortcuts: x op= y variables
item)
Example: x += 1 increments x os.curdir String with path of current
More String Operations directory
s.lower() lowercase copy of s import sys; print(sys.argv) or
from sys import argv; print(argv)
s.replace(old, copy of s with old replaced
new) with new
s.split( delim ) list of substrings delimited by
delim
By sschaub Published 21st May, 2012. Sponsored by CrosswordCheats.com
cheatography.com/sschaub/ Last updated 2nd June, 2014. Learn to solve cryptic crosswords!
Page 1 of 2. http://crosswordcheats.com
Essential Python Cheat Sheet
by sschaub via cheatography.com/1000/cs/374/
String Formatting
"Hello, {0} {1}".format("abe", "jones")
Hello, abe jones
"Hello, {fn} {ln}".format(fn="abe", ln="jones")
Hello, abe jones
"You owe me ${0:,.2f}".format(253422.3)
You owe me $253,422.30
now = datetime.now()
'{:%Y-%m-%d %H:%M:%S}'.format(now)
2012-05-16 15:04:33
See also http://docs.python.org/library/string.html#format-
specification-mini-language
Useful Functions
exit( code ) Terminate program with exit code
raw_input("prompt") Print prompt and readline() from stdin1
1 Use input("p
rompt") in Python 3
Code Snippets
Loop Over Sequence
for index, value in enumerate(seq):
print("{} : {}".format(index, value))
Loop Over Dictionary
for key in sorted(dict):
print(dict[key])
Read a File
with open("filename", "r") as f:
for line in f:
line = line.rstrip("\n") # Strip newline
print(line)
Other References
http://rgruet.free.fr/
Great Python 2.x Quick Reference
http://www.cheatography.com/davechild/cheat-sheets/python/
More Python Cheatsheet Goodness
By sschaub Published 21st May, 2012. Sponsored by CrosswordCheats.com
cheatography.com/sschaub/ Last updated 2nd June, 2014. Learn to solve cryptic crosswords!
Page 2 of 2. http://crosswordcheats.com