I plan to use Python as one of my main programming language for its huge numbers of libraries.
last update 2015-8-14
data.setdefault('names', []).append('Ruby')
data.get('foo', 0) # not data['foo']
[3*x for x in vec if x > 3] # [(x, x**2) for x in vec]
iterate for x, y in data.iteritems():
for x, y in zip(a, b):
z.lower() # upper()
s.isalpha() # s.isdigit()
s.split(" ") "-".join("GNU/Linux is great".split(" "))
s.strip() # s.lstrip("cwsd.") s.rstrip("cwsd.")
s.find("for") # s.startswith("fa") # s.endwith("fa")
s[::-1] # s.reverse()
'tea␣for␣too '. replace ('too ', 'two ')
s.join(s2) is faster than s + s2
"%s\n" % s is faster than s + "\n" . and "{0}\n".format(s) is recommended.
str.isspace()
str.ljust(width[, fillchar]) str.center(width[, fillchar]) str.rjust(width[, fillchar])
isdisjoint(other), issubset(other), issuperset(other)
``union(other, …), intersection(other, …), difference(other, …)
`update(other, …), add(elem), discard(elem)
sort
dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0}
dict= sorted(dic.iteritems(), key=lambda d:d[1], reverse = True) # by value
# [('aa', 74), ('a', 31), ('bc', 5), ('asd', 4), ('c', 3), ('d', 0)]
dict= sorted(dic.iteritems(), key=lambda d:d[0]) # by key
import cPickle
import pickle
a = range(10000)
%timeit -n 100 x = cPickle.dumps(a)
%timeit -n 100 x = pickle.dumps(a)
100 loops, best of 3: 1.58 ms per loop
100 loops, best of 3: 17 ms per loop
def change(b):
global a
>>> with open('setup.py') as fobj:
... for line in fobj:
... print line,
sys.stderr.write
shutil.copyfile(src, dst, *, follow_symlinks=True)
shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False)
shutil.move(src, dst)
shutil.rmtree(path, ignore_errors=False, onerror=None)
try:
do_some_func()
except KeyboardInterrupt:
print "User Press Ctrl+C,Exit"
except EOFError:
print "User Press Ctrl+D,Exit"
>>> a, b, *rest = range(10)
>>> a
0
>>> b
1
>>> rest
[2, 3, 4, 5, 6, 7, 8, 9]
Get the first and last lines of a file:
>>> with open('using_python_to_profit.txt') as f:
first, *_, last = f.readlines()
>>> first
'Step 1: Use Python 3\n'
>>> last
'Step 10: Profit!\n'