Python Index

Those who can, do.
Those who can't, teach.
Those who can't teach, write Python Indexes


Of if that sounds, too disparaging,
these be the function calls I find most useful.




Actually, I've been meaning to do this for awhile: a recap of the Python Documentation, reduced to the sections and functions I use (or want to use), but without any of the stuff I consider too basic to mention and/or so complicated or obscure I haven't found the need for it yet. So, like, if I were to write a program, these are the basic blocks I'd be most likely to use.



Built-in Functions
dir([object]) object's attributes as list
vars([object]) object's attributes as dictionary
locals() only if vars() didn't help
globals()
divmod(a,b) a/b, returns quotient & remainder
enumerate([list]) numbered generator, list(enumerate) returns a numbered list
filter(function, iterable) returns a filtered list
isinstance(object, classinfo) import types; type.FunctionType (or whatever, lots of help in types.)
len(a) returns it's length
map(function, iterable) equivelent to = [function(x) for x in iterable]
open(name, mode) text=open("f.txt","r").read(), "r"=read,"w"=write,"a"=append
ord(c) chr(ord(c))==c, ord is #, chr is letter
range(start,stop,step) inclusive of start, exclusive of stop
raw_input(prompt_text personally, I never use
reduce(function, iterable, initializer) like a fold
repr(object) returns string representation of object
sorted(list) returns new sorted list, sorted(list).reversed() being handy
set(iterable) list of unique elements
slice(start,stop,step) a[a:b:c] notation giving the same thing as a.slice(a,b,c)
zip([a,b,c],[d,e,f] yields [(a,d),(b,e),(c,f)], I've yet to have a call for it



Built-In Constants
[...] a=[], a=[a], a=[...], similar to Haskel's cannot construct infinite type



Built-in Types
is object identity, same object a is a = True
divmod(x,y) (x//y, x%y)
s.index(x) index of x, first occurance
s.count(x) how many x in s
"hello world".capitalize() "Hello world"
"Hello {0}".format("World!") "Hello World!"
"Hello w".replace("w","World!" "Hello World!"
"1".rjust(4,"0") "0001", " " space is default
"Hello ".strip("oH") "ello", left side
"Hello".rstrip("lo") "He", while endswith in "lo" strip end (right side)
"Hello World!".split(" ") ["Hello","World!"]
str.splitlines([keepends]) [line,line,line]
"hello to the world!".title() "Hello To The World!"
"1".zfill(4) "0001", so a specialized rjust()
str.sort() sorts in place, return = None
str.reverse() reverses in place, return = None



set
set([0,0,1,2,2]) set([0, 1, 2])
x in s is x in set
set.isdisjoint(set) no overlap, set([0,0,1,2,2]).isdisjoint(set([4,5,6])) = True
a.issubset(b) (<=)all a in b, set([0,1]).issubset([0,1,2]) = True
a.issuperset(b) (>=)all b in a, set([0,1,2]).issuperset([0,1]) = True
set(a) & set(b) intersection, set that is in both
set(a) | set(b) union, or, set from either, or, and both
set(a) - set(b) the difference
set(a) ^ set(b) xor, exclusive or, one or the other, not both
set.add(X) adds to set in place, nothing returned
set.remove(X) removes element from set in place, nothing returned
set.pop() returns and removes random element from set



Dictionaries
dict = {"key":"value",} no penalty for trailing comma
len(dict) number of items
dict["key"] returns "value", dict.key also sometimes works
dict["key"] = "newValue" sets key
"key" in dict returns True
dict.get("key") returns "value" or None if "key" doesn't exist
dict.items() returns list of (key,value) pairs
dict.keys() returns a list of keys in dictionary
dict.pop("key") return and remove (key,value) pair for passed key
dict.popitem() pop (return and remove) random (key, value) pair
dict.update(dict2) updates dict with values from dict2
dict.values() returns a list of values (no keys)
views, viewitems(), viewkeys(), viewvalues() opposite of a closure or copy, provides a dynamically updated view of dictionary, so as dictionary changes, so do the views
&, |, -, ^, work with views & = intersection, | = union, - = difference, ^ xor



Files Objects with open("txt.txt", "r") as f:
    text = f.read()
Opens file, returns contents, closes file, "r"=read, "w"=write, "a"=append
open("txt.txt") opens file
file.read() reads entire file, my prefered method
file.close() closes, housekeeping, hardly ever any negative consequences on short script if skipped
file.readline() returns next line, my files aren't that big
file.readlines() returns list of lines, so like read().splitlines()
file.write(string) writes string to file, note mode "w"=new this session, "a"=appends to pre-existing



String Constants
string.ascii_letters UPPER & lower
string.ascii_uppercase 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.ascii_lowercase 'abcdefghijklmnopqrstuvwxyz'
string.digits '0123456789'
string.printable
string.whitespace



String Formatting
"{} {}".format("Hello","World!") "Hello World!"
"{0} {1}".format("Hello","World!") "Hello World!"
"{h} {w}".format(h="Hello",w="World!") "Hello World!"
d = datetime.datetime(2015, 1, 17, 9, 5, 5)
'{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-01-17 09:05:05'
"{:0>4}".format(1) 0001
"{:X<4}".format(1) 1XXX
"{:,}".format(12345) 12,345
"${:,}".format(12345.67) $12,345.67
"{:.2%}".format(11/13.0) 84.62%



String Templates
from string import Template
d = {'first':"Brett", 'last':"Paufler"}
name = Template('$first $last')
print name.substitute(d)
"Brett Paufler", safe_substitute() ignores missing



Regular Expressions import re
re.findall(pattern, string) returns a list, this is overwhelming what I want
re.match(pattern, string) Finds at start of string only
text = "this dog is fine"
m = re.match(pattern, text)
if m:
    print m.group(0)
pattern='this', prints 'this'
pattern='dog', nothing is printed
re.search(pattern, string) same as match, but finds anywhere in string
re.sub(pattern, new, string) like string.replace(new, old)
re.findall(pattern, string, flags)
flags=(re.IGNORECASE | re.DOTALL)
. any but newline
^ start of string
$ end of string
X* 0 or more 'X'
X+ 1 or more 'X'
X? 0 or 1 'X'
[0-9a-d]{0,4} 0-4 of character in range []
|, [0-9]{1} | [a-zA-Z]{1,2} '|' is either/or, 1 number or 2 letters



codecs
# -*- coding: utf-8 -*- at first line of py file enables use of utf-8 in file
codecs.decode(text, 'ascii', 'ignore') returns text as ascii string, ignoring those out of range
Python 3.4 is Unicode Base So, use it if Unicode is important



datetime
import datetime

d = datetime.datetime.now()

print d
print d.year
print d.month
print d.day
print d.hour
print d.minute
print d.second
print d.microsecond




2015-01-22 18:45:08.365000
2015
1
22
18
45
8
365000
d += datetime.timedelta(days=1) 2015-01-23 18:45:08.365000
timedelta takes weeks, days, hours, minutes, seconds, microseconds, milliseconds
td = datetime.timedelta(minutes=3, hours=2)
print td.total_seconds()
7380.0
import datetime

d = datetime.date(2015,1,22)
t = datetime.date(2015,1,23)
print d
print t
print t - d
print d.year
print d.month
print d.day
print d.timetuple()
2015-01-22
2015-01-23
1 day, 0:00:00
2015
1
22
time.struct_time(tm_year=2015, tm_mon=1, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=22, tm_isdst=-1)
2015-01-22 19:00:00
d.weekday() Monday 0, Sunday 6
d.isoweekday() Monday 1, Sunday 7



8.3 collections



8.4 heapq



8.5 bisect
bisect.bisect like case select, only for ranges
grade = 'FDCBA'
y = grade[bisect.bisect([60,70,80,90], x)]
y = 'F' if x<60
y = 'D' if x<70, etc.



A working resource in progress: https://docs.python.org/2/library/collections.html


List Comprehensions
[a*b for a,b in zip(firstList, secondList)]
[a*b for a,b in zip([1,2], [0,1])] == [0, 2]






www.paufler.net


Copyright 2015 Brett Paufler
All information derived one way or another from docs.python.org
Brett@Paufler.net
Terms of Service