Вы находитесь на странице: 1из 3

Strings - Immutable

S = '\\' OR '\a'
S.capitalize()
S.casefold()
S.center(width [, f ill])
S.isalnum()
S.isalpha()
S.isdecimal()
S.isdigit()
S.isidentif ier()
S.islower()
S.isnumeric()
S.isprintable()
S.isspace()
S.istitle()
S.isupper()
S.join(iterable)
S.ljust(width, 'f ill')
S.lower()
S.lstrip([chars])
S.partition(sep)
S.rjust(width [, f ill])
S.rpartition(sep)
S.rstrip([chars])
S.strip([chars])
S.swapcase()
S.title()
S.translate(in,out)
S.upper()
S.zf ill(width)
S.list()

Escape sequence (search for more)


Capitalize f irst char
Normalize, lowercase
Centers (length, f ill char)
True if 1+ alphanumeric chars
True if 1+ alpha chars
True if all decimal chars
True if all digit chars
True is all char lower case
True if all char are numeric
True if chars are printable
True if only whitespace chars
True if f irst char uppercase
True if all chars uppercase
S is placed b/w iterable values
String length=width, replaces f ill @ left
Changes all chars to lower case
Removes chars from left part of string
Divides string at 1st sep. char->tuple
String length=width, replaces f ill @ right
Divides string at last sep. char->tuple
Removes chars from right part of string
Strips all chars from string
Inverts the case of all chars
Makes only f irst char uppercase
Maps in char and changes to out
Changes all chars to upper case
Fills string with zeros on left to (width)
Convert string into list of chars

Lists-Mutable
**Assign values to position**
L[i][j]
Access list value
L.len()
Returns length
A= L[:]
A copies all values of L
L.append(x)
Adds element to end
L.extend([x,y,z])
Concatenates the lists
L.insert(i,x)
Insert at value or range
L.index(x)
Return index position
L.count(x)
range(x,y,z)
x to y linspace w/ z space
L.sort(func)
Sorts by alpha (or, func)
L.pop()
Delete and return last item
L.reverse()
Reverses list- changes L
D=list(zip(['x','y'],[1,2])) Zips/fuses vars to values
L.copy()
Create copy. Not a reference
**Be sure to consider Shared References issues**
Object Classif ication:
Object Type Category
Mutable
Numbers (all) Numeric
No
Strings (all)
Sequence
No
Lists
Sequence
Yes
Dictionaries
Mapping
Yes
Tuples
Sequence
No
Files
Extension
N/A
Sets
Set
Yes
frozenset
Set
No
bytearray
Sequence
Yes

Comparisons, Equality, & Truth


==
Tests for equivalence
Is
Tests for object identity
**Do they live at same memory address
S.f ind(s, sub[, start[, end]])
Returns left position of s in string
True Vs. False
S.rf ind(s, sub[, start[, end]])
Returns right position of s in string
**If object is empty, then its considered false
S.splitlines([keepends])
Splits line breaks in string into list
Sets
S.rsplit([sep[,maxsplit]])
Splits string based on char (right 1st)
Items = set()
Creates an empty set
S.split([sep [,maxsplit]])
Splits string based on char (left 1st)
Items.add()
Adds 1 value to set
S.replace(old, new [, count]
Replaces old with new at max count
Items=set([x,y]) Creates set from list
S.rindex(sub [, start [, end]])
Same as f ind but returns error if N/A
Items.discard(x)Removes specif ci value
S.maketrans(x[, y[, z]])
Returns translate table for translate()
Items.pop()
Removes f irst value in the set
S.count(sub [, start [, end]])
Counts char in string in given range
X-y
Difference b/w 2 sets
S.encode([encoding [,errors]])
Sets text encoding to use
f=frozenset(list) Creates an Immutable set
S.endswith(suff ix [, start [, end]]) True if suff ix in given range
X in s
X member of S
S.startswith(pref ix [, start [, end]]) True if pref ix in given range
X not in s
X not a member of S
Isdisjoint()
Test if sets have no common
Slice
Format
x.Issubset(y)
Another subset test
[:3] 0 to 2
%(qty)d more %(food)s' % {'qty': 1, 'food': 'spam'} Set <= other
Test if all set in other
[5:] 5 to end
template='{0}, {1} and {2}'
Set < other
Test set is subset of other
[-1:] end-1 to end
template.format('spam','ham','eggs')
Set >= other
Test if all other in set
[:-1] 0 to end-1
'{:>10} = {:<10}'.format('spam', 123.4567)
Set > other
Test set is superset of other
**Many ways to format. eg. '{0:X}, {1:o}, {2:b}'.format(255, 255, 255)
Set | Other
Values in
That formats into hex, octal, binary... **dict_name => unpacks dict values Set & Other
Set intersection
e.g. '{name_0} {job_0} {name_1}'.format(**dict_name)
Set ^ Other
Values distinct to set or other

Loops
For, while, while... else,
While x: Loops till no no more X
while true: Loops till hits break
Break:
Closes current loop
Continue: Jumps to top of loop
Pass:
Empty placeholder
Iterations
x=iter(L) Create an iterable
x.__next__()
Try: check= iter(x) Iterable check
L=[x for x in ['x','','y'] if bool(x)]

Python- Built In Types

Dictionaries-Mutable
**Assign values to keys**
D={'title':'x',name'':'y'}
C = D.copy()
Copy values from D to C
D.keys()
Creates list of keys
D.items()
List of key + value(s) pairs
sorted(D1.items())
Sorted list of key value pair
D.values()
Creates list of values
D.clear()
Clears all values from list
D.update(D2)
Adds key value pair (D2) to D
D.get(key, default?)
Returns value assoc. with key
D.pop(key, default?)
Removes value assoc w. key
D.popitem()
Removes arbitrary (key, value)
D=dict(zip(['x','y'],[1,2])) Creates dict with 2 lists
D.keys() & D.keys()
D1 > OR < OR == D2 Compare dict magnitude
D[2]= 'test'
Can use int keys
D.copy.deepcopy()
Copies values, not references
**D
Unpacks dictionary
D={x:x**2 for x in range(5)} Create dict with loop
D.setdefault(key,default?) Look with key, if no use default
D={'cto':{'title':'x',name'':'y'}} Create nested dict

Python Major (Built-In) Functions


HELP-->
dir(function)
Lists attributes
help(sys)
Module help
abs()
all()
any()
basestring()
bin()
bool()
bytearray()
callable()
chr()
classmethod()
cmp()
compile()
complex()
delattr()
dict()
dir()
divmod()
enumerate()
eval()
execf ile()
f ile()
Tuples-Immutable
f ilter()
**Positionally ordered collection of objects**
f loat()
T=(0, 'bob', 3)
format()
Q= [x*2 for x in T]
frozenset()
T.index('x')
getattr()
T.count('x')
globals()
Namedtuple() create instance of namedtuple
hasattr()
cat=collections.namedtuple(cat, [name],[id])
hash()
cat_1= cat('Fluff les',1234)
help()
T=tuple(list)
Create tuple from list
hex()
id()
input()
int()
Files
isinstance()
Output= open(r'C:\spam', 'w')
Create f ile (w=write)
issubclass()
Input= open('data', 'r')
Create input f ile(r=read)
iter()
aString= input.read(N)
Read upto N char into string
len()
aString= input.readline()
Read next line into string
list()
aList= input.readlines()
Read entire f ile in list of strings
locals()
Output.write(aString)
Write string of chars into f ile
long()
Output.writelines(aList)
Write string list into f ile
map()
Output.close()
Manual f ile close
max()
Output.f lush()
Flush output buffer
memoryview()
AnyFile.seek(N)
Change f ile position to N (next op) min()
for line in open('data'): use line File iterator by line
next()
Open('f.bin', 'rb')
Read byte f iles
object()
r=open('data.bin','rb').read()
Open f ile & read binary
oct()
Codecs.open('f.txt', encoding='utf-8')
*Py 2.x f ile encoding
open()
**Use PICKLE module to store any Python object in a f ile
ord()
**Use JSON module to store data in json format
pow()

range()
raw_input()
reduce()
reload()
repr()
reversed()
round()
set()
setattr()
slice()
sorted()
staticmethod()
str()
sum()
super()
tuple()
type()
unichr()
unicode()
vars()
xrange()
zip()
__import__()
apply()
buffer()
coerce()
Intern()
print()
property()
Python Statements
=
Assignment
Pass
Empty placeholder (if, else)
Break
Loop exit
Continue
Continue Loop
Def
Create function and method
Return
function results
Yield
Generator. Value not stored.
Global
Create global function
Nonlocal
Only in 3.x
Class
Create a class
Try/except/f inally
Catching exceptions
Raise
Trigger exception
Assert
Debugging checks
With/As
Similar to try... f inally
Del
Delete references
**Many more, but obvious (eg. For)
If Statements
If, elif, else
Same functionality
A= [z,y][bool(x)] Another way of writing if else
If not
Inverts if logic

Functions
Modules Continued
*Functions are executed at runtime and created using def
*If variable @ top level of module starts with _
not imported with
Each function call creates a new local scope
from statement
*Factory Functions OR Closures are used to generate event
*__main__ indicates a f iles being executed form top level script
handlers on the f ly.
Object Orientated Programming
*Using arguments like *args OR **kargs (lists and dict respectively) *Inheritance in python built around object.attribute
has advantage of not needing to know # of args beforehand
*Attribute fetches can be thought of as tree fetches
*Argument may be passed by order or assignment
Classes: Attributes provide behavior. Top level attr. assign
*Use global vars only when needed
Instances: concrete items in program domain. Attr assign __self__
*Each function should have a single unif ied purpose
__init__ : used as constructor in python. If used with self.var1
*Function is an object. Can be assigned to var
the variable is available for lifetime of object
*dir(module) lists function names
*OOP: override generic class behavior by creating a method with
Lambda Functions
the same name but lower in class tree
**lambda function is not bound to a name, ex:
Ex. : Class subclass(superclass)
g= lambda x: x**2
*Created branched lambda functions
*When augmenting methods/ Customizing behavior:
*Useful when you need code to be close to where you are working Class Manager(Person):
{1: (lambda: 2+2), 2: (lambda: 2*4), 3: (lambda: 2**6)}[key]()
Def giveCheck(self, percent, bonus):
*Insert if else control f low
Person.giveCheck(self, paycheck+bonus)
lower = (lambda x, y: x if x < y else y)
**Good factoring: inherit original method form class
*Action = (lambda x: (lambda y: x + y)) **initialize action w. #
*list(map((lambda x: x+3),values))
*Customizing constructors def __init__(self, name, job=none):
*list(f ilter((lambda x: x>3),values)) **Filters values per condition
Class Manager(Person):
Map
Def __init__(self, name):
*Map is very powerful. It takes a set of values as an input for a
Person.__init__(self,name,'mgr')
function. Can use a lambda or function to generate the values too. **only redef ine constructor where it is needed
***MAPS AND LIST COMPREHENSIONS ARE FASTER***
Tom= Manager('Tom Jones', 50000) *no need to specify job
List Comprehension
**[M[row][col] * N[row][col] for row in range(3) for col in range(3)]** **All classes have the following meta methods**
*Parenthesis: Used to create a generator
Class.__dict__: class namespace
*Brackets: Used to Create a list
Class.__doc__: documentation string
Generators
Class.__name__: class name
*Generators make use of yield to output values one at a time and Class.__module__: module name where class def ined
avoids storage costs. Ephemeral values. Single iteration objects Class.__bases__: tuple of base classes
Example: ** x= gensquare(4)
next(x)
output=0
Def gensquare(N):
Common Operator Overloading
Common Operator Overloading
For I in range x:
__init__
constructor, object creation
__ior__ OR operator, store value in left var
yield x**2
__del__
destructor, object reclamation
__radd__
Used if __add__ fails
*Can use send() to pass a value outside of queue
__or__
operator, OR, |, |=
__iadd__
Operator, +=
Ex: x.send(4) output
0, 16
__add__
operator, +
__iter__, __next__
used for iteration
Time - Performance
__repr, __str__
printing or output
__contains__ membership test
Import timer
timer.total() OR timer.bestof()
__call__
call object instance as Function
__index__
Can use the Pystones module
__getattr__
fetch attribute, Ex: X.fetch
__enter__, __exit__
Modules
__setattr__
assign instance attribute
__get__, __set__
_init_.py
declares and initializes a regular module package
__delattr__
delete attribute. Ex: del X.any
__delete__
Descriptor attributes
*Modules should have unif ied purpose
__getattribute__
invoke before getattr*
__new__
-Helpful Module Internals: (Build programs about programs)__getitem__
extract item from iterable
Ex 1: Scipy.mean
__setitem__
place item in iterable
Ex 2: Scipy.__dict__['scipy']
__delattr__
delete item in iterable
Ex 3: sys.modules['scipy'].mean
__len__
get length
Ex 4: getattr(scipy, 'name')
__lt__,__gt__
comaprisons, >, <
*Can import using exec() command
exec(''import '+'scipy')
__le__, __ge__
comparisons, <=, >=
*Also use: imp = __import__('scipy') **faster
__eq__, __ne__
comparisons, ==, !=
*Also use: imp = scipy.import_module('mean')

Вам также может понравиться