3.2字元串格式化使用字元串格式化操作符即百分号%來實作
>>>format = "hello,%s.%s enough for ya?"
>>>values = ('world','Hot')
>>>print format % values
hello,world.Hot enough for ya?
>>>
格式化字元串的%s部分稱為轉換說明符,它們标記了需要插入轉換值的位置.s表示值會被格式化為字元串----如果不是字元串,則會用str将其轉換為字元串.
如果要格式化字元串字元串裡面包括百分号,那麼必須使用%%
如果格式化實數,可以使用f說明符類型,同時提供所需要的精度
>>> format = "pi with three decimals:%.3f"
>>> from math import pi
>>> print format % pi
pi with three decimals:3.142
string子產品提供另外一種格式化值得方法:模闆字元串.它的工作方式類似于很多unix shell裡的變量替換.substitute這個模闆方法會用傳遞進來的關鍵字參數foo替換字元串中的$foo
>>> from string import Template
>>> s = Template('$x,glorious $x!')
>>> s.substitute(x='slurm')
'slurm,glorious slurm!'
如果替換字段是單詞的一部分,那麼參數名就必須用括号起來,進而準确指明結尾:
>>> s = Template("It's ${x}tastic!")
"It's slurmtastic!"
可以使用$$插入美元符号:
>>> s = Template("Make $$ selling $x!")
'Make $ selling slurm!'
除了關鍵字參數之外,還可以使用字典變量提供值/名稱對:
>>> s = Template('A $thing must never $action.')
>>> d = {}
>>> d['thing'] = 'gentleman'
>>> d['action'] = 'show his socks'
>>> s.substitute(d)
'A gentleman must never show his socks.'
3.3字元串格式化:完整版
格式化操作符的右操作數可以是任何東西,如果是元組或映射類型,那麼字元串格式化将會有所不同.
如果需要轉換的元組作為轉換表達式的一部分存在,那麼必須将它用圓括号括起來,以避免出錯.
>>> '%s plus %s equals %s' % (1,1,2)
'1 plus 1 equals 2'
1.%字元:标記轉換說明符的開始
2.轉換标志:-表示左對齊;+表示在轉換值之前要加上正負号;""表示正數之前保留白格;0表示轉換值若位數不夠則用0填充
3.最小字段寬度:轉換後的字元串至少應該具有該值指定的寬度.如果是*.則寬度會從值元組中讀出.
4.點(.)後跟精度值:如果轉換的是實數,精度值就表示出現在小數點後的位數.如果轉換的是字元串,那麼該數字就表示最大字段寬度.如果是*,那麼精度将會從元組中讀出
5.轉換類型 見書 3-1 表
3-1-1簡單轉換
>>> 'Price of eggs:$%d' % 42
'Price of eggs:$42'
>>> 'Hexadeciaml price of eggs: %x' % 42
'Hexadeciaml price of eggs: 2a'
>>> 'Pi:%f...' % pi
'Pi:3.141593...'
>>> 'Very inexact estimate of pi: %i' %pi
'Very inexact estimate of pi: 3'
>>> 'Using str: %s' % 42L
'Using str: 42'
>>> 'Using repr: %s' % 42L
'Using repr: 42'
3.3.2字段寬度和精度
轉換說明符可以包括字段寬度和精度.字段寬度是轉換後的值所保留的最小字元個數,精度則是結果中應該包含的小數位數,或者是轉換後的值所能包含的最大字元個數
>>> '%10f' % pi 字段寬10
' 3.141593'
>>> '%10.2f' % pi 字段寬10 精度2
' 3.14'
>>> '%.2f' % pi 精度2
'3.14'
>>> '%.5s' % 'Guido van Rossum'
'Guido'
可以使用* 作為字段寬度或精度,此時數值會從元組參數中讀出:
>>> '%.*s' % (5, 'Guido van Rossum')
>>> '%*.*s' % (10,5, 'Guido van Rossum')
' Guido'
3.3.3符号,對其和0填充
>>> '%010.2f' % pi
'0000003.14'
3-1字元串格式化示例
#!/usr/bin/env python
width = input('Please enter 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)
3.4字元串方法
盡管字元串方法完全來源于string子產品,但是這個子產品還包括一些不能作為字元串方法使用的常量和函數.maketrans函數就是其中之一,後面會将它和translate方法一起介紹,下面是一些有用的字元串常量
string.digits:包括數字0~9的字元串
string.letters:包含所有字母的字元串
string.lowercase:包含所有小寫字母的字元串
string.printable:包含所有可列印字元的字元串
string.punctuation:包含所有标點的字元串
string.uppercase:包含所有大寫字母的字元串
3.4.1 find
find方法可以在一個較長的字元串中查找子字元串。它傳回子串所在位置的最左端索引。如果沒有找到則傳回-1
>>> 'With a moo-moo here,and a moo-moo there'.find('moo')
7
>>> title = "Monty Python's Flying Circus"
>>> title.find('Monty')
>>> title.find('Python')
6
>>> title.find('Flying')
15
>>> title.find('Zirquss')
-1
可選的起始點和結束點參數
>>> subject = '$$$ Get rich now!!! $$$'
>>> subject.find('$$$')
>>> subject.find('$$$',1)
20
>>> subject.find('!!!')
16
>>> subject.find('!!!',0,16)
3.4.2 join
join方法是非常重要的字元串方法,它是split方法的逆方法,用來在隊列中添加元素。
>>> 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
需要添加的隊列元素都必須是字元串。
3.4.3 lower
lower方法傳回字元串的小寫字母版
>>> 'Trondheim Hammer Dance'.lower()
'trondheim hammer dance'
>>> name = 'Gumby'
>>> names = ['gumby','smith','jones']
>>> if name.lower() in names: print 'Found it'
...
Found it
另一個string子產品的capwords函數
>>> string.capwords("that's all,folks")
"That's All,folks"
3.4.4 replace
replace方法傳回某字元串的所有比對項均被替換之後得到字元串
>>> 'This is a test'.replace('is','eez')
'Theez eez a test'
3.4.5 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']
3.4.6 strip
傳回除兩側空格的字元串:
>>> ' inernal whitespace is kept '.strip()
'inernal whitespace is kept'
它和lower方法一起使用的話就可以很友善的對比輸入的和存儲的值.讓我們回到lower部分中的使用者名的例子,假設使用者在輸入名字時無意中在名字後面加上了空格:
>>> name = 'gumby '
>>> if name in names : print 'Found it'
>>> if name.strip() in names: print 'Found it'
也可以指定需要去除的字元,将它們列為參數即可.
>>> '***SPAM*for*everyone!!!***'.strip('*!')
'SPAM*for*everyone'
3.4.7 translate
translate方法和replace方法一樣,可以替換字元串中的某些部分,但是和前者不同的是,translate方法隻處理單個字元.它的優勢在于可以同時進行多個替換,有些時候比replace效率高的多.
在使用translate轉換之前,需要先完成一張轉換表.轉換表中是以字元替換某字元的對應關系.因為這個表有多達256個項目,我們還是不要自己寫了,使用string子產品裡面的maketrans函數就行.
maketrans函數接受兩個參數:兩個等長的字元串,表示第一個字元串中的每個字元都用第二個字元串中相同位置的字元替換.
>>> from string import maketrans
>>> table = maketrans('cs','kz')
>>> len(table)
256
>>> table[97:123]
'abkdefghijklmnopqrztuvwxyz' 字母c和s 分别替換成kz
>>> maketrans('','')[97:123]
'abcdefghijklmnopqrstuvwxyz'
建立這個表以後,可以将它用作translate方法的參數,進行字元串的轉換如下:
>>> 'this is an incredible test'.translate(table)
'thiz iz an inkredible tezt'
translate的第二個參數是可選的,這個參數是用來指定需要删除的字元.
>>> 'this is an incredible test'.translate(table,' ')
'thizizaninkredibletezt'
非英語字元串的問題
有些時候類似于lower這樣的字元串方法并不能如我們所願地進行工作.
本文轉自潘闊 51CTO部落格,原文連結:http://blog.51cto.com/pankuo/1634648,如需轉載請自行聯系原作者