0x01 Format string
替換規則
replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name ::= arg_name ("." attribute_name | "[" element_index "]")*
arg_name ::= [identifier | integer]
attribute_name ::= identifier
element_index ::= integer | index_string
index_string ::= <any source character except "]"> +
conversion ::= "r" | "s"
format_spec ::= Format Specification
replacement_field Example
"First, thou shalt count to {0}" # References first positional argument
"Bring me a {}" # Implicitly references the first positional - argument
"From {} to {}" # Same as "From {0} to {1}"
"My quest is {name}" # References keyword argument 'name'
"Weight in tons {0.weight}" # 'weight' attribute of first positional arg
"Units destroyed: {players[0]}" # First element of keyword argument 'players'.
個人理解:可以按照順序進行格式化,其中需要進行替代的參數只要能夠獲取到就行。
例如:
>>> c = 3-5j
>>> ('The complex number {0} is formed from the real part {0.real} '
... 'and the imaginary part {0.imag}.').format(c)
'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
>>> class Point(object):
... def __init__(self, x, y):
... self.x, self.y = x, y
... def __str__(self):
... return 'Point({self.x}, {self.y})'.format(self=self)
...
>>> str(Point(4, 2))
'Point(4, 2)'
conversion
在某些情況下,需要把格式化的參數先替換成字符串,然後再進行格式化,這樣,conversion參數就有用武之地了。
Two conversion flags are currently supported: '!s' which calls str() on the value, and '!r' which calls repr().
現僅支持兩類conversion標識:"!s"和"!r", "!s"會調用替換值得str(),而'!r'則會調用repr()
"Harold's a clever {0!s}" # Calls str() on the argument first
"Bring out the holy {name!r}" # Calls repr() on the argument first
0x02 Format Specification Mini-Language
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" | "%"
fill option
在有對齊的情況下,對空格進行替換的字符,可以是任何字符。
align options
Option | Meaning |
---|---|
'<' | 左對齊 |
'>' | 右對齊 |
'^' | 居中對齊 |
'=' | 僅對數字有效 |
>>> '{:<30}'.format('left aligned')
'left aligned '
>>> '{:>30}'.format('right aligned')
' right aligned'
>>> '{:^30}'.format('centered')
' centered '
>>> '{:*^30}'.format('centered') # use '*' as a fill char
'***********centered***********'
>>> b="{:0=20}"
>>> b.format(11)
'00000000000000000011'
>>> b.format(-1)
'-0000000000000000001'
>>> b.format(+1)
'00000000000000000001'
>>> a="{:<20}"
>>> a.format(1)
'1 '
>>> b="{:<20}"
>>> b="{:=20}"
>>> b.format(1)
' 1'
sign options
sign option只對數字類型的數字有效,有以下幾種:
- '+': indicates that a sign should be used for both positive as well as negative numbers.無論正負數,都會加上正負號。
- '-': indicates that a sign should be used only for negative numbers (this is the default behavior).只有在數字爲負數時會添加上負號
-
space: indicates that a leading space should be used on positive numbers, and a minus sign on negative numbers.在正數前面有個空格,在負數前面是個負號
>>> '{:+f}; {:+f}'.format(3.14, -3.14) # show it always '+3.140000; -3.140000' >>> '{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers ' 3.140000; -3.140000' >>> '{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}' '3.140000; -3.140000'
'#' option
僅對整型數據有效,並且只能輸出二進制、八進制或十六進制的轉換數據,獲得的輸出數據前綴依次是'0b', '0o', 或'0x'。
>>> # format also supports binary numbers
>>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
'int: 42; hex: 2a; oct: 52; bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
',' option
此可選參數表示格式化需要千位分隔符','。在本地化的分隔符中,用'n'整型表示類型來代替。
>>> '{:,}'.format(1234567890)
'1,234,567,890'
width option
width is a decimal integer defining the minimum field width. If not specified, then the field width will be determined by the content.
width選項,是一個十進制整型數據,用來定義字段的最短寬度。如果沒有指定,那麼字段的寬度將由字段本身的內容決定。
precision option
precision是一個十進制數據
- 當一個浮點型數據需要被格式化'f'、'F'時,小數點後面需要保留的位數。
- 當一個浮點型數據需要被格式化'g'、'G'時,小數點前後總共的位數。
- 當一個非數字的字段需要被格式化時,表示最大保留的字段長度,即字段中多少個字符會被使用
不能對整型數據使用
type option:
type參數需要分情況使用
string類型數據
Type | Meaning |
---|---|
's' | 字符串格式化。字符串的默認類型。可能被取代。 |
None | 同's'. |
整型數據格式化
Type | Meaning |
---|---|
'b' | 轉化爲2進制。 |
'c' | 轉化爲unicode字符. |
'd' | 轉化爲10進制。 |
'o' | 轉化爲8進制 |
'x' | 轉化爲16進制,小寫 |
'X' | 轉化爲16進制,大寫 |
'n' | 數字. 同'd', except that it uses the current locale setting to insert the appropriate number separator characters. |
None | 同'd'. |
浮點型數據格式化
Type | Meaning |
---|---|
'e' | 指數標識。使用科學計數法,默認精度爲6. |
'E' | 同'e',只是把指數標識換成了'E'. |
'f' | 固定精度的浮點型. 默認精度是6. |
'F' | 同'f'. |
'g' | 見'g'解釋 |
'G' | 同'g',例外情況:except switches to 'E' if the number gets too large. The representations of infinity and NaN are uppercased, too. |
'n' | Number. 同'g', except that it uses the current locale setting to insert the appropriate number separator characters. |
'%' | 百分比轉換 |
None | 同'g'. |
'g'解釋
General format. For a given precision p >= 1, this rounds the number to p significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude.
一般的格式化。如果給定的精度p>=1,這將對數字p進行四捨五入,然後根據大小將結果格式化爲固定精度的數據或是科學計數的數據。
精度的規則爲:將結果格式化爲科學計數e和精度爲p-1的表達式exp。如果-4<=exp<p,那麼數據將會轉化爲'f'類型,並且精度爲p-1。如果-4>exp,那麼數據將會被格式化爲'e'類型,精度爲p-1.在這兩種情況中,末尾的0將會移除,如果沒有小數,小數點也會移除>> '{:.10g}'.format(0.00097867008822282723426) '0.0009786700882' >> '{:.10g}'.format(0.000097867008822282723426) '9.786700882e-05' >> '{:.10g}'.format(0.0000900) '9e-05' >> '{:.10g}'.format(0.000900) '0.0009' >> '{:.10g}'.format(0.0000900) '9e-05' >> '{:.10g}'.format(0.0000000097867008822282723426) '9.786700882e-09'
正負無窮,正0負0和 nans將會依次被格式化爲inf,-inf,0, -0,不管精度爲何值。
精度0將被看做和精度1相同。默認的精度爲6
日期格式化
>>>
>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'