python除了string內建的功能之外,還有其他玩法,更重要的是配合其他內建的資料結構,像是list, tuple, dictionary進而產生強大的功能。以下就是一點點示範。     
      
      
字串連結和複製 ('+', '*' )                   
>>> print 'a' + 'b' + 'c'        
abc        
>>> print 'abc' * 3        
abcabcabc        
字串插入 ( tuple ,dictionary )        
用tuple插入:                   
>>> print '%s %s %s' %( 'a' , 'b' , 'c' )        
a b c        
也可以把template存成字串,等待被插入:                   
>>> template = '%s %s %s'        
>>> print template % ( 'a', 'b' , 'c' )        
a b c        
用字典插入:       
                   
>>> temp_dict = '%(first)s %(second)s %(third)s'        
>>> intp_dict = { 'first' : 'how' ,        
'second' : 'are',        
'third' : 'you',        
}        
>>> print temp_dict % intp_dict        
how are you        
字串分解和結合 ( list )      
用space來分割字串:                   
>>> s1 = 'how are you'        
>>> s1.split()        
['how', 'are', 'you']        
        
>>> a = s1.split()        
>>> print a        
['how', 'are', 'you']        
用減號來組合字串:                   
>>> '-'.join(a)        
'how-are-you'        
再示範一次      
      
依照換行符號來分割:                   
>>> s1 = '''first line        
second line        
end line'''        
        
>>> a = s1.split( '\n' )        
>>> print a        
['first line', 'second line', 'end line']        
用逗號組合回去 :                   
>>> s_comma = ','.join(a)        
>>> print s_comma        
first line,second line,end line        
用逗號分割:                   
>>> s_comma_a = s_comma.split(',')        
>>> print s_comma_a        
['first line', 'second line', 'end line']        
用換行符號組合回去 :                   
>>> print '\n'.join( s_comma_a )        
first line        
second line        
end line        
  
2007年11月29日 星期四
python 玩字串
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言