Python字符串格式化


一、使用格式化符來格式化字符串:

Python支持的所有格式化符

格式化符 意義
'd' 返回要格式化對象的十進制表示,如果可以
'i' 返回要格式化對象的十進制表示,如果可以
'o' 返回要格式化對象的八進制表示,如果可以
'u' 同格式化符'd'
'x' 返回要格式化對象的十六進制表示,如果可以【如果要求的前導,使用'0x'】
'X' 返回要格式化對象的十六進制表示,如果可以【如果要求的前導,使用'0X'】
'e' 返回要格式化對象的浮點的科學計數的表示,如果可以【使用'e'】
'E' 返回要格式化對象的浮點的科學計數的表示,如果可以【使用'E'】
'f' 返回要格式化對象的浮點數表示,如果可以
'F' 返回要格式化對象的浮點數表示,如果可以
'g' 使用小寫字母科學計數格式,如果指數小於-4或不少於精度,否則返回十進制格式。
'G' 使用大寫字母科學計數格式,如果指數小於-4或不少於精度,否則返回十進制格式。
'c' 對0-255之間的整數返回其對應的ASCII碼字符(其它整數報錯),或者返回單個字符本身
'r' 返回要格式化對象的__repr__()方法的返回值
's' 返回要格式化對象的__str__()方法的返回值
'%' 即每兩個%顯示一個

1.%s格式化符:將要格式化的值表中對應位置的元素,格式化為字符串,如果值元素不是字符串,將自動調用該元素的__str__(),以得到其字符串表示。

[1]%ns決定對齊與填充:n為整數;當n>0時,左填充,當n<0時,右填充。

 1 >>> for i,x in enumerate(('one','two','three','four','five','six')):
 2     print '%5s = %d'%(x,i)
 3 
 4     
 5   one = 0
 6   two = 1
 7 three = 2
 8  four = 3
 9  five = 4
10   six = 5
11 >>> 

[2]%.ns決定對字符串的截取:n為正整數

 1 >>> for i,x in enumerate(('one','two','three','four','five','six')):
 2     print '%.3s = %d'%(x,i)
 3 
 4     
 5 one = 0
 6 two = 1
 7 thr = 2
 8 fou = 3
 9 fiv = 4
10 six = 5
11 >>> 

2.%d格式化符:將任何Python對象轉化為整數,如果轉化失敗,則報錯。

[1]%nd:決定對齊與填充。n為整數;當n>0時,左填充,當n<0時,右填充。

1 >>> print '%3d'%1.52
2   1
3 >>> 

[2]%0nd:以數字0而不是默認的空格來作填充。

1 >>> print '%03d'%1.52
2 001
3 >>> 

[3]%+d:數字被轉化后將保留正負號

1 >>> print '%+d'%1.52
2 +1
3 >>> print '%+d'%-1.52
4 -1
5 >>> print '%+3d'%1.52
6  +1
7 >>> print '%+03d'%1.52
8 +01
9 >>> 

3.%r格式化符:將任何Python對象轉化成repr字符串,自動調用Python對象的__repr__()

[1]%nr:決定對齊與填充。n為整數;當n>0時,左填充,當n<0時,右填充。

1 >>> print 'Names = #%50r#'%(['C','CPP','CSharp','Java','Python'])
2 Names = #          ['C', 'CPP', 'CSharp', 'Java', 'Python']#
3 >>> print 'Names = #%-50r#'%(['C','CPP','CSharp','Java','Python'])
4 Names = #['C', 'CPP', 'CSharp', 'Java', 'Python']          #
5 >>> 

[2]%.nr:決定截取字符數。n為正整數

1 >>> print 'Names = #%.10r#'%(['C','CPP','CSharp','Java','Python'])
2 Names = #['C', 'CPP#
3 >>> 

4.%o與%x格式化符:將十進制數值格式化為八進制與十六進制字符串;當有'#'時,格式化后的字符串帶前導

 1 >>> '%x'%20
 2 '14'
 3 >>> '%#x'%20
 4 '0x14'
 5 >>> '%#X'%20    #使用X作前綴,如果使用#要求了前綴
 6 '0X14'
 7 >>> '%o'%10
 8 '12'
 9 >>> '%#o'%10
10 '012'
11 >>> 

注意:如果要格式化的數值是浮點數,將先取整,再格式化

1 >>> '%o'%13.2
2 '15'
3 >>> '%x'%20.3232
4 '14'
5 >>> '%x'%20.5232
6 '14'
7 >>> 

5.%f格式化符:以浮點數格式化數值。

[1]%nf:格式化數字后填充到固定寬度;當n>0時,左填充,當n<0時,右填充。【若不指定小數位數時,最小寬度8位,如'0.000000'】

1 >>> '%20f'%32
2 '           32.000000'
3 >>> '%-20f'%32
4 '32.000000           '
5 >>> 

[2]%.nf:格式化數字后的小數位數;n>=0且為整數

1 >>> '%.3f'%0.3245
2 '0.325'
3 >>> '%.0f'%0.3233
4 '0'
5 >>> '%.8f'%0.3245
6 '0.32450000'
7 >>> 

6.%e格式化符:以浮點科學計數的方式轉化數值,即10的指數冪形式

[1]%ne:將格式化后的數字字符串進行填充到指定寬度;當n>0時,左填充,當n<0時,右填充。【如不指定小數位數,最小寬度是12位,如'0.000000e+00'】

1 >>> '%15e'%8283489323232
2 '   8.283489e+12'
3 >>> '%-15e'%8283489323232
4 '8.283489e+12   '
5 >>> 

[2]%.ne:指定小數位數;n>=0且為整數。

1 >>> '%.10e'%82834
2 '8.2834000000e+04'
3 >>> '%.2e'%8283489323232
4 '8.28e+12'
5 >>> 

7.%c格式化符:將0-255之間的數字轉化成對應的ASCII碼字符,也可以轉化單個字符,不過基本不做什么,直接返回

1 >>> '%c'%32
2 ' '
3 >>> print '%c'%'A'
4 A
5 >>> print '%c'%8
6 
7 >>> 

【上面的第五行的語句在這里顯示不了結果,請在IDLE或者shell中執行,就可看到結果】

8.其它格式化符,因為不同情況下有不同表現,所以不常用,如果你清楚其工作方式,自己選用吧。

二、使用str.format(*args, **kwargs)方法來格式化字符串

1.序數占位符:

1 >>> '{0} is our new {1}, welcome {0}.'.format('Tom','teacher')
2 'Tom is our new teacher, welcome Tom.'
3 >>> args=('Tom','teacher')
4 >>> '{0} is our new {1}, welcome {0}.'.format(*args)
5 'Tom is our new teacher, welcome Tom.'
6 >>> 

2.命名占位符:

1 >>> '{name} is a lovly girl, she likes {fruit} and {food}.'.format(name='Lily',fruit='apple',food='rice')
2 'Lily is a lovly girl, she likes apple and rice.'
3 >>> kws=dict(name='Lily',fruit='apple',food='rice')
4 >>> kws
5 {'food': 'rice', 'fruit': 'apple', 'name': 'Lily'}
6 >>> '{name} is a lovly girl, she likes {fruit} and {food}.'.format(**kws)
7 'Lily is a lovly girl, she likes apple and rice.'
8 >>> 

3.以上兩種可以混用,且序數占位符的序數可以不給出,即使用空占位符形式,它會自動從零起開始給空占位符編序號,但切記空占位符不能與編了序數的占位符混用。

 1 >>> '{} is a boy, {} is {age}.'.format('Tom','he',age=12)
 2 'Tom is a boy, he is 12.'
 3 >>> numbers=('one','two','three','four','five','six','seven')
 4 >>> 'I love the numbers: {3},{5}.'.format(0,*numbers) #0只是占個位,方便選擇第3、5個元素
 5 'I love the numbers: three,five.'
 6 >>> '{0} is a boy, {} is {age}.'.format('Tom','he',age=12)
 7 
 8 Traceback (most recent call last):
 9   File "<pyshell#11>", line 1, in <module>
10     '{0} is a boy, {} is {age}.'.format('Tom','he',age=12)
11 ValueError: cannot switch from manual field specification to automatic field numbering
12 >>> 

4.支持內部格式語法,即{:xxx}這種語法

format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]
fill        ::= <any character>
align       ::= "<" | ">" | "=" | "^"
sign        ::= "+" | "-" | " "
width       ::= integer
precision   ::= integer
type        ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

[1]align填充之對齊標記:

align char Meaning
'<' 在右邊填充
'>' 在左邊填充
'=' 填充時強制在正負號與數字之間進行填充,只支持對數字的填充
'^' 在兩邊填充
 1 >>> for align, text in zip('<^>', ['left', 'center', 'right']):
 2     print 'fill = align = %r, text = %r, output:'%(align,text)
 3     print '{0:{fill}{align}16}'.format(text, fill=align, align=align)
 4     print
 5 
 6     
 7 fill = align = '<', text = 'left', output:
 8 left<<<<<<<<<<<<
 9 
10 fill = align = '^', text = 'center', output:
11 ^^^^^center^^^^^
12 
13 fill = align = '>', text = 'right', output:
14 >>>>>>>>>>>right
15 
16 >>> def sy():
17     a,b=12345,8794
18     print '{: =6}'.format(a)
19     print '{: =+6}'.format(b)
20     print '-'*6
21     print '{: =6}'.format(a+b)
22 
23     
24 >>> sy()
25  12345
26 + 8794
27 ------
28  21139
29 >>> 

 [2]sign數字之前導標記:

sign char Meaning
'+' 強制對數字使用正負號
'-' 僅對負數使用前導負號(這是默認的行為)
' ' 對正數使用一個' '作前導,負數仍以'-'為前導

【參見上例】

[3]#被用來與type為'b'/'o'/'x'/'X'合作,對整數進行格式化,格式化后數字前分別以'0b'/'0o'/'0x'/'0X'為前導

1 >>> #str.format支持數值向二進制格式化,是使用%進行字符串格式化所無法做到的
2 >>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
3 'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
4 >>> #如上str.format支持對同一Python對象進行多次不同格式化
5 >>> #使用'#'時,將會自動給各種格式化結果加上前導,如果有前導
6 >>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
7 'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'
8 >>>

[4]','被用來對數字整數部分進行千分位分隔

1 >>> '{:,}'.format(1234567890)
2 '1,234,567,890'
3 >>> 

[5].precision對於數字對象,用來指定數字的小數位數,如果有小數;對於非數字對象,用來指定最終返回的格式化字符的最大長度,即格式化完成后,以這個precision參數對結果進行截取

 1 >>> '{:.2f}'.format(3.235)
 2 '3.23'
 3 >>> '{:.2}'.format('hello')
 4 'he'
 5 >>> '%.2f'%3.235
 6 '3.23'
 7 >>> '%.2f'%3.2353
 8 '3.24'
 9 >>> '{:.2f}'.format(3.2351)
10 '3.24'
11 >>> 

[6]type用來指定格式化時的轉換方式

<1>當要格式化的Python對象是str對象時

Type Meaning
's' 字符串格式,這是默認格式
None 與's'相同,即原數據是str類型,且不指定type時,將采用默認的's'格式
1 >>> print '{{0:}}=={{0:s}}\n{0:}=={0:s}'.format('hello')
2 {0:}=={0:s}
3 hello==hello
4 >>> 

由上面的例子可見,在str.format()方法的調用中,兩個'{'顯示出一個,兩個'}'也顯示出一個

<2>當要格式化的Python對象是integer對象時

Type Meaning
'b' 將數值轉換成二進制字符串
'c' 將數值轉換成對應的unicode字符,比%c強多了,它支持0-255之外的字符
'd' 十進制數值
'o' 八進制數值
'x' 十六進制數值,如果要求前綴,則使用0x
'X' 十六進制數值,如果要求前綴,則使用0X
'n' 同'd'
None 在原數值為整數時,如果又沒有指定type,則此時使用'd'作為type

【參見例子2.4.3】

<3>當要格式化的Python對象是浮點數對象時

Type Meaning
'e' 科學計數,使用字母'e',默認精度6
'E' 科學計數,使用字母'E',默認精度6
'f' 浮點數,默認精度6
'F' 浮點數,默認精度6
'g' 很難用,棄之不說
'G' 同'g'
'n' 同'g'
'%' 對原數值乘以100后,加上'%’作后綴
None 同'g'

【因為'g'的用法難以掌握,且規則復雜,而'e'/'f'/'%'已經足夠使用了,所以這里就棄之不說了,有興趣的可以自行研究】

1 >>> '{:f}'.format(32.3863)
2 '32.386300'
3 >>> '{:e}'.format(3738)
4 '3.738000e+03'
5 >>> '{:.2%}'.format(100/365.0)
6 '27.40%'
7 >>> 

5.使用要格式化對象的屬性來進行格式化

1 >>> from collections import namedtuple
2 >>> Point=namedtuple('Point','X Y')
3 >>> p=Point(3,7)
4 >>> p
5 Point(X=3, Y=7)
6 >>> 'Point({p.X}, {p.Y})'.format(p=p)
7 'Point(3, 7)'
8 >>> 

6.使用要格式化對象的項來進行格式化

1 >>> person=('Bill',23,'male')
2 >>> "Name: {0[0]}, Age: {0[1]}, Sex: {0[2]}".format(person)
3 'Name: Bill, Age: 23, Sex: male'
4 >>> 

7.使用{!r}和{!s}取得%r和%s的效果

 1 >>> '{!r},{!s}'.format('hello','world')
 2 "'hello',world"
 3 >>> #下面的無法成功,表明其它格式化符並不支持這種搞法
 4 >>> '{!d}'.format(32)
 5 
 6 Traceback (most recent call last):
 7   File "<pyshell#19>", line 1, in <module>
 8     '{!d}'.format(32)
 9 ValueError: Unknown conversion specifier d
10 >>> 

8.如果要格式化的Python對象擁有自己的格式化字符,那么也可以用這個對象的格式化符進行format

1 >>> import datetime
2 >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
3 >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
4 '2010-07-04 12:15:58'

三、str.format的基礎——Format String Syntax,其定義如下:

1 replacement_field ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"
2 field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*
3 arg_name          ::=  [identifier | integer]
4 attribute_name    ::= identifier 5 element_index     ::= integer | index_string 6 index_string      ::=  <any source character except "]"> +
7 conversion        ::=  "r" | "s"
8 format_spec       ::=  <described in the previous section>

1.通過第1、2行,可知上面的2.5與2.6的語法基礎,而arg_name既可以是成員訪問形式的標識符也可以是索引訪問形式的序數,所以

[1]2.5的例子可以改為:

1 >>> from collections import namedtuple
2 >>> Point=namedtuple('Point','X Y')
3 >>> p=Point(3,7)
4 >>> p
5 Point(X=3, Y=7)
6 >>> 'Point({0.X}, {0.Y})'.format(p)
7 'Point(3, 7)'
8 >>> 

[2]2.6的例子可以改為:

1 >>> person=('Bill',23,'male')
2 >>> "Name: {person[0]}, Age: {person[1]}, Sex: {person[2]}".format(person=person)
3 'Name: Bill, Age: 23, Sex: male'
4 >>> 

2.通過第5行,可以知道element_index既可以是整數索引也可以是字符串索引,所以也可以使用字典的字符串鍵來索引字典的值

1 >>> person={'name':'Bill','age':23,'sex':'male'}
2 >>> "Name: {0[name]}, Age: {0[age]}, Sex: {0[sex]}".format(person)
3 'Name: Bill, Age: 23, Sex: male'
4 >>> 

【要注意的是,占位符中的字符串索引必須不帶字符串定界符】

3.通過第1、7行,可知占位符中只允許出現!r和!s兩種,其它都不支持;而它的前后也可以有其它內容,來進行更細節的格式化控制;每個!r或!s占位符分別對對應的要被格式化的值調用obj.__repr__()或obj.__str__()

1 >>> 'The variable value is {0!r},{0!r:.3}'.format('hello')
2 "The variable value is 'hello','he"
3 >>> 

四、應用技巧

1.多級格式化:使用內部自轉義,'%%'=>'%','{{'=>'{','}}'=>'}'

1 >>> '%s, %%s' % 'Hello' % 'Gates'
2 'Hello, Gates'
3 >>> '{greet},{{name}}'.format(greet='Hello').format(name='Gates')
4 'Hello,Gates'
5 >>> '%%%ds'%10%'fuck'
6 '      fuck'
7 >>> 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM