1. format of strings
'{dog} is called {name}'.format(dog='doggy', name='jk')
# output: 'doggy' is called jk
2.
>>> print '\101' #oct
A
>>> print '\x41'
A
3. sort the list
>>> b = [[1, 2], [4, 1], [5, 2], [-1, 4]]
>>> b
[[1, 2], [4, 1], [5, 2], [-1, 4]]
>>> b.sort(key=lambda x:x[1]) #here x refers to each element of list b. Obviously x is also a list. Sorting according to x[1]'s value
>>> b
[[4, 1], [1, 2], [5, 2], [-1, 4]]
>>> b.sort(key=lambda x:x[0])
>>> b
[[-1, 4], [1, 2], [4, 1], [5, 2]]
4. Deep Copy in python
Note: the following can just deep copy the top level of the elements. As to the lower structure inside the list and dcit, only the references will be copied.
>>> L = [1, 2, 3]
>>> A = L[:] #deep copy
>>> A
[1, 2, 3]
>>> A[2] = 'jkk'
>>> A
[1, 2, 'jkk']
>>> D = {'a': 2, 'b': 1}
>>> B = D.copy()
>>> B['2'] = 3
>>> D
{'a': 2, 'b': 1}
>>> B
{'a': 2, '2': 3, 'b': 1}
5. Complete Deep Copy
import copy
b = copy.deepcopy(a) # deep copy of all level structure
6 try catch, error print and traceback
def catchError():
try:
a = 3/0
except Exception as e:
logging.traceback.print_exc()
7. output content into a file
>>> print >> open("a.txt", "w"), "HE"*100
# write the string content into a.txt file