Low Orbit Flux Logo 2 D

Python Cheat Sheet

WARNING - No descriptions or explainations. If you want to learn and need guidance, CHECK OUR FULL PYTHON TUTORIAL HERE.

Purpose: This is a cheat sheet. It is NOT meant to teach you Python. It is meant as a reference to help you remember syntax. It helps if you find yourself asking things like, “How do you check the length of an array?” or “What is that regex match character?”. We don’t cover everything, just the basics to get things done fast (no classes, eggs, threads, etc.).

Get the PDF right HERE

Get it as an image HERE

List / Array

p = [1, q, 4]create list
p[2] = xassign
x = a.pop()pop
len(a)get length
Comparison Operators

in, not in, is, is not, and, or, notIdentity
== != > < >= <= Value
Dictionary / Hash

d = {'b’ : 1, 'a' : 2 }dict
d['abc'] = 14.50assign
len(d)get length
del d[key_name]remove key and value
d.remove(value)first item with value
for key in map1:loop over dict
Flow Control and Loops

if x < 0:
elif x == 0:
while b < 10:while loop
while True:infinite loop
for w in words:"normal" for loop
for i in range(len(a)):array with indices
for i in range(5, 10):5-9
for k,d in enumerate(a):dict, loop key/val


File Management

import osOS module
import shutilSome utils
shutil.copy(src, dst)Copy file
os.rename(src, dst)rename file
os.unlink("/tmp/foo.txt")delete file
os.listdir("/dir")List files
os.mkdir(path[, mode])Create directory
shutil.copy(src, dst)copy content and permission
os.rmdir(path)remove dir, only empty dirs
os.removedirs(path)remove empty dir, recursive

File IO

f = open('workfile', 'w')r or w
f.write('This is a test\n')write
f.read()entire file
f.readline()line at a time
f.readlines()entire file, as list
f.close()close it

Function Syntax
def function1(one, two='Yes', *name2, **name3):           
    return value
Subprocess / Run OS Commands
import subprocess
subprocess.check_output( "uname -a", stderr=subprocess.STDOUT, shell=True )

Regular Expressions

Basic Usage

p = re.compile(r”match this”)     
m = p.search('string goes here')
if m:
    print 'Match found: ', m.group()
    print 'No match'
# r for raw string
# array of tuples
# includes groups
p = re.compile('(a(b)c)d')     
# nested groups
p = re.compile(r'\W+')
p.split('test test')
# split, return list
p = re.compile( '(blue|white|red)')
x = p.sub( 'colour', 'blue socks and red shoes')
p = re.compile('ab*', re.I | re.M)case insensitive, multi-line

Regular Expressions Characters

\ddecimal digit [0-9]
\swhitespace [ \t\n\r\f\v]
\walphanumeric [a-zA-Z0-9_]
.any character except newline
*0 or more
+1 or more
?0 or 1


re.SMake . match any char, including newlines
re.IDo case-insensitive matches
re.MMulti-line matching, affecting ^ and $