Author: Rick Copland
Date: 6/3/2014
- zip enumerate
- eval
- dir help
- chr ord
- map filter
- sum, max, min & len
- repr
repr
<=> eval
dir(x)
help(x)
-
with docstring
-
x._doc_
ord('a')
√
ord(u'你好')
√
chr(97)
√
map(func, elements)
i.e.
map(ord, 'FOO')
filter(func, sequences)
i.e.
def is_even(num): return num % 2 ==0
filter(is_even, xrange(10))
pass
repr
, for programmerstr
, printunicode
, print
In short, repr
is for debugging; str
is for uers
more
int('5')
int('ff', 16)
float('5')
list([1,2,3])
tuple([1,2,3])
items = [(0, 'a'), (1, 'b')]
dict(items)
keys = range(4)
values['a', 'b', 'c', '4']
dict(zip(keys, values))
dict(foo=1, bar=2, baz=3)
unicode('abcd')
dir(__builtins__)
- open
- sys
- os
-
open
fp = open('/etc/hosts') print repr(fp.read(40)) fp.close() # does not load the whole file in memory for line in fp: print repr(line) fp.close() # gives the number of liens fp.readlines() list(open('/etc/hosts')) fp.read() fp.seek() fp.tell()
-
mode
# r for read # w for write # a for append # w+ for write with reading # r+ for reading with writing fp = open('/ect/hosts', 'r')
-
encodings
-
python2. read with bytestring
-
python3. read with bytes
-
Side notes:
-
Raw String r('h/e/l/l/o/\w\o\r\l\d!')
-
with open
includes automatically close -
isinstance(), type()
Python Module
- The import statment
- sys -- inspect the running process
- os -- inspect the operating system
- math -- floating point math function
- time and datetim
- files and the StringIO module
alias
-
import sys as mysys
-
from sys import path
-
from sys import path as p
-
from datetime import datetime, day, time
-
more
sys.argv sys.executable sys.stdin sys.stdout sys.stderr # print right way in case sys crushed
Side notes:
help(sys.setprofile)
-> useful for debuging
sys.maxint
import os
dir(os)
fd.open('ls -l')
print fd.read()
print os.path
dir(os.path)
os.normpath('/usr/local/bin/../../bin')
os.path.expanduser('~')
os.path.expandvars('$HOME is here')
import math
help(math)
impor time
time.time() # epoch time
time.asctime() # readable
time.ctime() # character time
time.gmtime() # UTC
time.mktime(time.gmtime())
time.localtime()
time.strftime('2012-11-05', '%Y-%m-%d')
time.strptime('2012-11-05', '%Y-%m-%d')
time.sleep(0.1) # in second time
import datetime
datetime.datetime.now()
now = datetime.datetime.utcnow()
print repr(now.date())
print repr(now.time())
time.mktime(now.timetuple()) # Epoch
-
Question: help vs dir?
Answer:
- dir gives the attributes
- help gives the docstring
-
Question: repr vs str?
Answer:
- repr for developers
- str for users
-
convert to truthy and falsy
Answer:
- not not
- bool()
-
which is cheaper fp.readlines() or list(open('/etc/hosts'))?
Answer:
- Write your own iterate loop, so it will discard the contents if one don't care.
- more
-
paths
os.env.path
(runs in subprocess)sys.path