Show Menu
Cheatography

Kingmold's Python Cheat Sheet (DRAFT) by

Python reference for the stuff Eric has trouble remembering.

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

String Methods

capita­lize()
Capita­lizes first letter of string
center­(width)
String is centered within X characters
endswi­th(sub)
True if string ends with substring
expand­tab­s(w­idth)
Turns \t into X blank spaces
find(sub, start, end)
Can just put in string as variable to find loc
index(sub start end)
Finds the index of a list or string
isalnum()
True if only letter or number (no spaces)
isalpha()
True if it's a letter
isdigit()
True if a number
islower()
True if all lowercase
isspace()
True if a space exists in the string
istitle()
True if first letter of each word is capita­lized
isupper()
True if all of string is upper case
join()
':'.jo­in(­list) would combine all with ':'
replac­e(old, new)
Replaces all instances of old with new
starts­wit­h(sub)
True if string starts with substring
rparti­tio­n(sub)
Turns string into 3 part tuple based on substr

Threading w/Thre­ading Module

import threading
t = threading.Thread(
target=func, args=(­arg1,))
t.start()
Start the thread right after thread­ing.Thread
thread­s.a­ppe­nd(t)
Appends thread to your defined list for sync
for threads in threads:
    threads.join()
Joins threads so they end at same time
 

Datetime Module

import datetime
dateti­me.t­od­ay(­).w­eek­day()
Returns 0 thru 6. 0 is Monday
dateti­me.t­od­ay(­).i­sow­eek­day()
Returns 0 thru 6. 1 is Monday
datetime.datetime.today()
.strftime('%A')
Returns name for day of the week
datetime.datetime.now()
.strftime("%H:%M:%S")
Returns hour minute and second of current time
dateti­me.d­at­eti­me.n­ow()
Datetime object of current time

Find time between two datetime objects

import datetime
first_time = dateti­me.d­at­eti­me.n­ow()
later_time = dateti­me.d­at­eti­me.n­ow()
difference = later_time - first_time
second­s_i­n_day = 24 * 60 * 60
divmod­(di­ffe­ren­ce.days * second­s_i­n_day + differ­enc­e.s­econds, 60)
Returns a tuple of minutes comma seconds ex. (8, 0)

sys.a­rgv for python foo.py bar -c qux --h

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

os Module

os.pat­h.i­sdi­r(loc)
True if loc is a directory
os.pat­h.i­sfi­le(loc)
True if loc is a file
os.pat­h.n­orm­pat­h(loc)
Gives path normalized for Win *
* Removes redundant separators and up-level references
 

Django Module

pip install Django
External module
django­-admin startp­roject mysite
Starts a new project folder called mysite
python manage.py runserver [ip][:­port]
Runs the project stuff in brackets is optional
python manage.py startapp blog
Creates applic­ation in your project folder called blog
python manage.py makemi­gra­tions blog
Propagates blog app changes to database
python manage.py migrate
Syncs database with new model
python manage.py create­sup­eruser
Creates a superuser, prompts will follow