#lists and tuples #list fragmentation d[x:y:z] #z is the step size # sequence add [1,2,3]+[4,5,6] [1,2,3,4,5,6] 'hello '+'world' 'hello world' [1,2,3]+'aa' #Error #multiplication 'python'*5 'pythonpythonpythonpythonpython' [None]*10 #Initialize a sequence of 10 lengths #membership a in b #f returns boolean # use string # String objects are immutable website[-3:]='dom' #Error #string formatting format='Hello,%s %s enough for ya?' values=('world','hot') print format % values #Hello,world hot enough for ya? """sequences will only be parsed as one value, only dictionaries and tuples can format more than one value If there is a % in the text, use %% to escape """ format='%.3f' #Format floating-point numbers, accurate 3 digits format='%10.3f' #Format floating point number, width 10, precise 3 digits format='%.5s' #The first five characters '%.*s' % (5,'guido van rossum') # *, width will be read in tuple, guido #0 padding '%010.2f'%pi '0000003.14' # left align '%-10.2f'%pi '3.14' #Add a space before positive numbers for alignment print('% 5d'%10)+'\n'+('% 5d'%-10)F 10 -10 # Whether positive or negative, add a sign print('%+5d'%10)+'\n'+('%+5d'%-10)F +10 -10 print '-'*10 #---------- #template string from string import Template s=Template('$x,glorious $x!') s.substitute(x='slurm') #slurm,glorious slurm! s=Template('It`s ${x}tastic!') #replace part of the word """ If there is $ in the text, use $$ to escape The argument to substitute() can be a dictionary The method safe_substitute() will not report an error due to the wrong use of $ """ #tuple '%s plus %s equals %s'%(1,1,2) 1 plus 1 equals 2 #string method #find 'asdfghjkl'.find('asd') #Return 0, if no query is found, return -1, otherwise return the leftmost index subject.find('aaa',1) #Provide starting point subject.find('aaa',1,10) #Provide starting point and ending point, including the first and not the second #join seq=[1,2,3,4,5] sep='+' sep.join(seq) #Error report, only a list of strings can be connected seq=['1','2','3','4','5'] sep.join(seq) '1+2+3+4+5' dirs='','usr','bin','env' '/'.join(dirs) '/usr/bin/env' print 'C:'+'\\'.join(dirs) C:\usr\bin\env #lower lowercase 'ABC'.lower() 'abc' #capitalization "that`s all folks".title() "That`S All Folks" import string string.capwords("that`s all folks") "That`s All Folks" #replace 'This is a test'.replace('is','eez') 'This ezz a test' #split '1+2+3+4+5'.split(+) ['1','2','3','4','5'] #strip remove spaces or characters from both sides 'asd '.strip() 'asd' #translate is the same as the replace method, but only processes a single character. The advantage is that multiple replacements can be performed at the same time, which is sometimes much more efficient than replace from string import makestrans table=makestrans('cs','kz') len (table) 256 table[97,123] 'abkdefghijklmnopqrztuvwxyz' #c and s are replaced by k and z, this table can be used as the parameter of translate makesrans('','')[97,123] 'abcdefghijklmnopqrstuvwxyz' 'this is an incredible test'.translate(table) 'thiz iz an inkredible' #translate(table[,s]) The second character is used to specify the delete character 'this is an incredible test'.translate(table,' ') 'thizizaninkredible' #dictionary #dict() function items=[('name','Gumby'),('age',42)] d=dict(items) d ['age':42,'name','Gumby'] d['name'] 'Gumby' #dict() can create a dictionary with keyword arguments d=dict(name='Gumby',age=42) #If dict() takes no arguments, create an empty dictionary #Common methods len(d) #return the number of key-value pairs d[k] #return the value corresponding to the k key d[k]=v #Associate the value to the key del d[k] #delete the item of key k k in d #Check if there is an item with key k in d #dictionary format string phonebook {'Beth':'9102','Alice':'2341','Cecil':'3258',} "Cecil`s phone number is %{Cecil}s"%phonebook "Cecil`s phone number is 3258" #dictionary method #clear d.clear() #Blue empty dictionary, the return value is none x={} y=x x['key']='value' and {'key':'value'} x.clear() #Operate on objects and {} #copy和deepcopy from copy import deepcopy d={} d['name']=['Alfred','Bertrand'] c=d.copy() dc=deepcopy(d) d[name].append('Clive') c {'name':{'Alfred','Bertrand','Clive'}} dc {'name':{'Alfred','Bertrand'}} #fromkeys initialize dictionary {}.fromkeys(['name','age']) {'age':None,'name':None} dict.fromkeys(['name','age'],'(unknow)') #Define the default value, which can be called directly on the dictionary type dict {'age':'(unknow)','name':'(unknow)'} #get d={} print d['name'] #error print d.get('name') None d.get('name','N/A') #define the default value 'N/A' #has_key() is equivalent to k in d, python3 does not contain this function d={} d.has_key('name') False #items and iteritems d={'a':'aa','b':'bb','c':'cc'} d.items() [('a','aa'),('b','bb'),('c','cc')] it=d.iteritems() #return iterator list(it) [('a','aa'),('b','bb'),('c','cc')] #Indeterminate order