Show Menu
Cheatography

Python Cheat Sheet by

Python cheat sheet all

Basics

abs()
absolute value
hash()
hash value
set()
creat a Set object
all()
True if all elements are true
any()
True if any element is true
min()
return minimum
max()
return maximum
divmod­(a,b)
return (a//b,a%b)
hex()
hexade­­cimal
oct()
octal
bin()
binary
dir()
return all attributes of obj
sorted(iter)
return a new sorted list from iter
open(p­ath­,mode)
open a file
int()
creat an Int object
str()
return the string form
float()
creat a float obj
list()
creat a List obj
isinst­anc­e(o­bj,­class)
check if obj belongs to class
ord(c)
return ASCII of c
chr(n)
return char of ASCII
sum(iter)
return sum of iter
filter­(pr­ed,­iter)
return list of elements meeting pred
pow(a,b)
return a^b
callab­le(obj)
True if obj is callable
type()
return type of obj
zip()
zip('a­­b'­,­'12') -> a1,b2
map(f,xs)
return ys = f(xs)
round()
rounded number

thread

import threading
t = thread­­in­g.T­h­r­ea­­d(t­­ar­g­e­t=­fun, args = iter­,­na­­me=­­thread name)
creat a thread
t.start()
start thread t
t.join()
join thread t, other threads waiting until t finishes
lock = thread­­in­g.L­ock()
create a lock
lock.a­­cq­u­ire()
current thread acquires the lock
lock.r­­el­e­ase()
current thead release lock

str-li­brary

s1+s2
string concat­enation
s*5
repeating 5 times of s
[0] or [:]
subscr­iption and slice
in/not in
member test
r/R
no escape: r'\n' = '\n' (no new line)
%
string formatting (%d <=> integer) )
s.capi­tal­ize()
capitalize the first char in s
s.coun­t(x­,be­g=0­,en­d=l­en(s)))
count the number of occurence of x in s
s.ends­wit­h(s­uff­ix,­beg­=0,­end­=le­n(s))
check if s ends with suffix (within the given area)
s.star­tsw­ith­(pr­efi­x,b­eg=­0,e­nd=­len(s))
check if s starts with x
s.expa­ndt­abs­(ta­bsi­ze=8)
expand the "­tab­" in s to space
s.find­(x,­beg­=0,­end­=le­n(s))
return start index of x in s if x is in s, else -1
s.inde­x(x­,be­g=0­,en­d=l­en(s))
similar to find, but raises an exception if x is not in s
s.rindex()
s.rfind()
s.isal­num()
True if every char(>=1) in s is number or letter
s.isal­pha()
True if every char(>=1) in s is letter
s.isdi­git()
True if every char(>=1) in s is number
s.isnu­meric()
True if all characters in the string are numeri­c(>=1)
s.isde­cimal()
Return True if the string is a decimal string­(>=1), False otherwise.
s.issp­ace()
True if s only contains space
s.join()
Concat­enate any number of strings using s as delimiter
s.upper()
all to uppercase
s.isup­per()
True if all cased chars are superc­ase­(>=1)
s.lower()
all to lowercase
s.islo­wer()
True if all cased chars are lowerc­ase­(>=1)
s.lstrip()
return a new string leading whitespace removed
s.strip()
Return a copy of the string with leading and trailing whitespace removed
s.rstrip()
Return a copy of the string with trailing whitespace removed.
s.spli­t(d­el,­max­split = s.coun­t(del))
Return a list of the words in the string, using del as the delimiter string
s.spli­tli­nes­(ke­epends)
Return a list of the lines in the string, breaking at line bounda­ries. Line breaks are not included in the resulting list unless keepends is given and true.
s.swap­case()
lower <-> upper
s.titile()
titili­zation: all words are capita­lized
s.repl­ace­(ol­d,new,max)
Return a copy with all occurr­ences of substring old replaced by new
 

list

[1,2,3­]+[­4,5,6]
[1,2,3­,4,5,6]
arr = [0]*10
Array arr = new Array[10]
l.appe­nd(obj)
append obj at end of l
l.coun­t(obj)
count occurence number of obj in l
l.extend(iter)
Extend list by appending elements from the iterable
l.inde­x(o­bj,­beg­=0,­end­=le­n(l))
Return first index of value. Raises ValueError if the value is not present
l.remo­ve(obj)
Remove first occurrence of value. Raises ValueError if the value is not present
l.sort­(cm­p=N­one­,ke­y=N­one­,re­ver­se=­False)

tuple

(1,2)+­(3,4)
(1,2,3,4)
(0)*10
(0,0,0­,0,­0,0­,0,­0,0,0)

dict (hasht­able)

d = {'age':20}
create a dict
d['age'] = 30
add/update value
d.pop(­­key)
deleting key and value
d.clear()
create a dict
d.get(­key­,de­fau­lt=­None)
get value by key, or default if key not exists
d.has_­key­(key)
True if d has key
d.items()
a list of (key,v­alue) of d
d.upda­te(d2)
updating (k,v) of d2 to d1
d.pop(key)
delete and return the value pointed by the key
d.popi­tem()
delete and return a pair of (k,v) randomly
dict features:
1. fast for searching and inserting, which won't be affected by the number of keys
2. occupy a lot of memory

set

s = set([1­­,2,3])
creat a set
s.add(4)
adding element
s.remo­­ve(4)
deleting element
s1 & s2
inters­­ection of sets
s1 | s2
union of sets
s.clear()
clear the set
s.pop()
remove one element randomly
s1.sym­met­ric­_di­ffe­ren­ce(s2)

copy

a = li
a: new pointer to li
a = li[:]
first level copy
a = list(li)
first level copy
a = copy.c­­op­y(li)
first level copy
a = copy.d­­ee­p­c­op­­y(li)
recursive copy
import copy
li = [1,2,3­­,[­4,5]]

list generation expression

[a+b for a in list1 for b in list2]

@property

class Student(object):
  @property
  def score(self): return 100

  @score.setter
  def score(self,value): pass
the three names (score) should be consistent

regular expression

import re
re.mat­ch(­pat­ter­n,s­tring,flags)
Try to apply the pattern at the start of the string, returning a Match object, or None if no match was found.
re.sea­rch­(pa­tte­rn,­string,flag)
Scan through string looking for a match to the pattern, returning a Match object, or None if no match was found.
matchO­bje­ct.s­pan()
return (a,b) where a is the start inex and b is the end index of the matching
re.com­pil­e(p­attern,flag)
Compile a regular expression pattern, returning a Pattern object, which can be used in re.mat­ch/­re.s­earch
 

parameters

func(*­­args)
accepting any parameters
func(**kw)
accepting only key word parameters

closure

def create_myFunc_at_runtime(*runtime_para):
  def myFunc(x):
    (return x + runtime_para)
    pass
  return myFunc

Build A Class: Test

__slots__ = ('name­­',­'­age')
this class have only 2 attributes now: name & age
__eq__­­(s­e­l­f,obj)
override "­­==­" operator
__ne__­­(s­e­l­f,obj)
!=
__le__­­(s­e­lf,o)
<=
__ge__­­(s­e­lf,o)
>=
__lt__­­(s­e­lf,o)
<
__gt__­­(s­e­lf,o)
>
__str_­­_(­self)
override str()
__repr­­__­(­self)
repr()
__len_­­_(­self)
len()
__geti­­te­m­_­_(­­self,n)
subscr­­itable and slice-able
__seti­­te­m­_­_(­­sel­­f,­k­e­y,­­value)
supporting item assignment
__call­­__­(­self)
-> callable

inheri­tance

overriding __init__:
super(child class,self).__init__(*para)

datetime

from datetime import datetime
dt = dateti­me(­201­5,4­,19­,12,20)
2015-04-19 12:20:00
dateti­me.n­ow()
current date and time
dateti­me.s­tr­pti­me(­'20­15-6-1 18:19:­59'­,'%­Y-%m-%d %H:%M:%S')
str -> datetime
dt.str­fti­me(­'%a,%b %d %H %M')
datetime -> str
from datetime import timedelta
datetime addition and subtra­ction
now + timede­lta­(hours = 10)
now + timede­lta­(da­ys=1)

JSON

import json
js=jso­n.d­ump­s(py)
convet from python obj to json
py = json.l­oad­s(js)
convert from json to python obj
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

            Python 3 Cheat Sheet by Finxter

          More Cheat Sheets by xys

          python thread Cheat Sheet
          Java Cheat Sheet
          HTML Cheat Sheet