python字符串格式化笔记

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'

0x03阅读文档

https://docs.python.org/2/library/string.html

猜你喜欢

转载自blog.csdn.net/qq_39469761/article/details/74939550