字符串操作
字符串在任何一門語言都是一個重點,靈活運用可實現各種強大的功能,在python中,字符串也是如此,標準的序列操作對字符串也使用,但是分片賦值不行,因爲字符串是不可變的。
字符串的格式化:
字符串格式化使用字符串格式化操作符%來實現,在%左側放置一個字符串,右側放置希望格式化的值。看下面這個簡單的例子:
>>> format="Hello,%s,I'm studying %s!"
>>> values=('world','Python')
>>> print format % values
Hello,world,I'm studying Python!
注意:如果使用列表或者其他列表代替元組,那麼序列就會被解釋爲一個值,只有元組和字典和格式化一個以上的值。
%s標記了需要插入轉換值的位置,s表示會被轉化爲字符串,如果不是字符串,則會用str將其轉換爲字符串。另外,如果需要在格式化字符串裏包括百分號,則必須使用%%。
如果需要格式化實數,用f說明符類型,同時提供精度;一個據點再加上希望保存的小數位數。因爲格式化說明符總是以表示類型的字符結束,所以精度應該放在類型字符前面:
>>> format="PI with three decimals :%.3f"
>>> from math import pi
>>> print format % pi
PI with three decimals :3.142
格式化操作符的右操作數可以是任何東西,如果是元組或者映射類型(字典),則字符串的格式化略有不同。例如,如果右操作數是元組,則其中每一個I元素都會被單獨格式化,每個值都需要一個對應的轉換說明符。(注意:如果需要轉換的元組作爲轉換表示的一部分存在,那麼必須將它用圓括號括起來)
>>> '%s plus %s equals %s ' %(1,1,2)
'1 plus 1 equals 2 '
當然,字符串格式化還有很多,比如填充和字寬和精度等,這些帶用到時再去查也不遲,下面是一個關於字符串格式化一個較綜合的例子,包括字寬和對齊等:
width = input ( 'Please input width:' )
price_width = 10
item_width = width - price_width
header_format = '%-*s%*s'
format = '%-*s%*.2f'
print '=' * width
print header_format % (item_width, 'Item' ,price_width , 'Price' )
print '-' * width
print format % (item_width , 'Apples' ,price_width , 0.4 )
print format % (item_width , 'Pears' ,price_width , 0.5 )
print format % (item_width , 'Cantaloupes' ,price_width , 1.92 )
print format % (item_width , 'Dried Apricots(16 oz.)' ,price_width , 8 )
print format % (item_width , 'Prunes(4 lbs.)' ,price_width , 12 )
print '=' * width
raw_input ( "enter any key to exit~~" )
|
運行結果如下:
字符串方法:
幾乎任何一種語言關於字符串的方法都很多,不過都大同小異,python中字符串方法的思想和數據結構的思想非常相似。
find——在一個較長的字符串查找子字符串,返回所在位置的最左端索引,下面是常用的用法:
>>> "hello,python,I like python" .find( 'python' ) #返回的是第一個‘python’的索引
6
>>> title = "hahha,hekko,hello"
>>> title.find ( 'find' ) #找不到時返回-1
- 1
>>> subject = '$$$ Get rich now !!!$$$'
>>> subject.find ( '$$$' ) #默認返回最左邊所在的位置
0
>>> subject.find ( '$$$' , 1 ) #指定起始搜索位置
20
>>> subject.find( '$$$' , 0 , 10 ) #指定搜索的上下限,注意包含上線不包含下線
0
|
join——用來在隊列中添加元素(必須是字符串),是split方法的逆方法,很常用,下面幾例是常見用法:
>>> digitals = [ 1 , 2 , 3 , 4 , 5 ]
>>> seperaor = '+'
>>> seperaor.join(digitals) #連接數字列表出現錯誤
Traceback (most recent call last):
File "<pyshell#9>" , line 1 , in <module>
seperaor.join(digitals)
TypeError: sequence item 0 : expected string, int found
>>> digitals = [ '1' , '2' , '3' , '4' , '5' ] #改爲字符串
>>> seperaor = '+'
>>> seperaor.join(digitals) #連接字符串列表是正確的
'1+2+3+4+5'
>>> dir = ' ',' usr ',' bin ',' env'
>>> '/' .join( dir ) #Linux下目錄的格式
'/usr/bin/env'
>>> print 'C:' + '\\' .join( dir ) #windows下目錄格式,注意反斜槓需要轉義
C:\usr\ bin \env
|
lower——返回字符串的小寫字母。爲了程序的友好有時候需要“忽略”用戶輸入的大小寫,在程序中應使用統一的格式來識別,下面舉出常見用法:(upper是類似的用法)
>>> 'Trouble Is a Friend!' .lower()
'trouble is a friend!'
>>> if 'Jzhou' in [ 'jason' , 'james' , 'jzhou' ]: #未轉換時沒有匹配
print 'Found it!'
>>> name = 'Jzhou'
>>> names = [ 'jason' , 'james' , 'jzhou' ]
>>> if name.lower() in names: #將轉換爲小寫進行匹配
print 'Found it!'
Found it!
>>>
|
title方法和string模塊的capwords函數可以將一句話的首字母大寫,符合標題習慣(對冠詞的處理不太合理)
>>> 'i like python' .title ()
'I Like Python'
>>> import string
>>> string.capwords ( "i like python!" )
'I Like Python!'
>>>
|
replace——返回字符串的所有匹配項均被替換之後得到的字符串
>>> 'this is a test' .replace( 'test' , 'work' )
'this is a work' #查找並替換
|
split——將字符串分割成序列,是join的逆方法,很常用
>>> '1+2+3+4+5' .split( '+' )
[ '1' , '2' , '3' , '4' , '5' ]
>>> '/usr/bin/env' .split( '/' )
[' ', ' usr ', ' bin ', ' env']
>>> 'Using the default' .split () #如果不提供任何分隔符,默認會把所有空格(包括空格、製表符、換行符等)作爲分隔符
[ 'Using' , 'the' , 'default' ]
|
strip(lstrip,rstrip)——返回出去兩側(不包括內部)空格的字符串,類似C#中的trim函數(ltrim,rtrim)
>>> ' internal whtiespace is kept ' .strip ()
'internal whtiespace is kept' #默認取出前後的空格
>>> names = [ 'jason' , 'james' , 'jzhou' ]
>>> name = ' jzhou' #前面有2個空格
>>> if name in names : print 'Found it!' #不匹配
>>> if name.strip() in names : print 'Found it!' #取出空格後匹配
Found it!
>>> '****!!SPAM** for ** everyone!!*******' .strip( '*!' ) #指定要去除的字符
'SPAM** for ** everyone'
>>>
|
translate——和replace方法一樣,可以替換字符串中的某些部分,但是和replace不同,它只處理單個字符,但同時可進行多個替換,有時效率比replace高。
使用translate轉換之前,需要先完成一張轉換表,轉換表中是以某字符的對應關係,這個表有多達256個項目,可以使用string模塊裏的maketrans函數得到。
maketrans函數有兩個參數:兩個等長的字符串,表示第一個字符串中的每個字符都用第二個字符串中相同位置的字符替換,如下例子:
>>> from string import maketrans
>>> table = maketrans( 'cs' , 'kz' ) #就是把table中的字符c換成k,字符s換成z
>>> len (table)
256
>>> table[ 97 : 123 ] #提取處理後的小寫字母部分,字符c和s已經被替換了
'abkdefghijklmnopqrztuvwxyz'
>>> maketrans (' ',' ')[ 97 : 123 ] #這是空轉換(即未轉換前)的消息字母部分
'abcdefghijklmnopqrstuvwxyz'
>>>
|
創建了這個table之後,可以將它用作translate方法的參數,進行字符串的轉換,如下:
>>> 'this is an incredibele test' .translate(table)
'thiz iz an inkredibele tezt'
|
translate的第二個參數是可選的,這個參數用來指定要刪除的字符,如將一句話中‘fuck’刪除:
>>> 'Hen,fuck is not a good word' .translate(table, 'fuck' )
'Hen, iz not a good word'
>>> 'Hen,fuck is not a good word' .translate(table, ' ' ) #將空格都刪除
'Hen,fukkiznotagoodword'
|
字符串的方法有很多,以上這些是比較常用的,可以用到時再去查。