s = 'abcd' int('123') # str to int # long(), float() str(123) # int to str ord(s[0]) # char to int chr(97) # int to char # unichar(97) # convert to char using unicode ENCODING list(s) # str to list ['a','b','c','d'] # tuple(s) hex(11) # int with base 10 to base 16 # oct(11)
2.sorting
1 2 3 4 5 6 7 8 9 10 11 12
a = ['b', 'c', 'd', 'a'] a.sort() # a = ['a', 'b', 'c', 'd'] # sort in place s = 'cbda' sorted(s) # ['a', 'b', 'c', 'd'] # sorted(iterable, cmp=None, key=None, reverse=False) --> return a new sorted list sorted([5, 2, 3, 1, 4], reverse=False) # [1, 2, 3, 4, 5] L = [('d',2),('a',4),('b',3),('c',2)] sorted(L, key=lambda x:(x[1],x[0])) # [('c', 2), ('d', 2), ('b', 3), ('a', 4)] sorted(L, cmp=lambda x,y:cmp(x[1],y[1])) # [('a', 1), ('b', 2), ('c', 3), ('d', 4)] sorted(L, key=lambda x:x[1])) # [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # use 'key' will be faster than 'cmp' # http://www.cnblogs.com/65702708/archive/2010/09/14/1826362.html
3.others
1 2 3 4 5 6 7 8 9
#read file f = open('text', 'r') for line in f: line = line.strip() # remove '\n', ' ' in the begin and end of the line # do something with line
a = set([1,2,3]) b = set([2,3,4]) a.intersection(b) # {2,3}