python的format格式化

使用方法:  '{}bbccc'.format(aa) = aabbcc, 用来代替python2中的%,即替换。

1、通过位置来指定替换

In [2]: '{0},{1}'.format('a', 'b')
Out[2]: 'a,b'

In [3]: '{1},{0}'.format('a', 'b')
Out[3]: 'b,a'

In [4]: '{},{}'.format('a', 'b')
Out[4]: 'a,b'

2、通过关键值参数来指定

In [5]: '{a},{b}'.format(a='d', b='e')
Out[5]: 'd,e'

In [6]: '{b},{a}'.format(a='d', b='e')
Out[6]: 'e,d'

3、通过列表或字典

In [7]: a = ['c', 'd']

In [8]: '{0[0]}, {0[1]}'.format(a)
Out[8]: 'c, d'

In [9]: '{n[0]}, {n[1]}'.format(a)   这里应该使用关键字参数
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-9-e2eb21499a9d> in <module>()
----> 1 '{n[0]}, {n[1]}'.format(a)
KeyError: 'n'

In [10]: '{n[0]}, {n[1]}'.format(n=a)
Out[10]: 'c, d'

In [11]: b = {'x': 1, 'y': 2}

In [12]: '{0[x]}, {0[y]}'.format(b)
Out[12]: '1, 2'

4、填从,对奇功能,

^, <, > 分别为居中,左对齐,右对齐,
In [13]: '{:^14}'.format('nnnn')   14指定这个str共多少个字符,
Out[13]: '     nnnn     '       ^ 为居中

In [14]: '{:>14}'.format('nnnn')   > 为右对齐
Out[14]: '          nnnn'

In [15]: '{:<14}'.format('nnnn')   < 为左对齐
Out[15]: 'nnnn          '

In [16]: '{:0<14}'.format('nnnn')  冒号后面根填从,
Out[16]: 'nnnn0000000000'

In [17]: '{:b<14}'.format('nnnn')
Out[17]: 'nnnnbbbbbbbbbb'

5、转换格式,

一个对象本身不是str,ascii,repr格式,可以使用!s、!a、!r,将其转成str,ascii,repr。

>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"

还有很多功能,请查看官网:https://docs.python.org/3/library/string.html#formatspec

比如:

>>> 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'

>>> points = 19
>>> total = 22
>>> 'Correct answers: {:.2%}'.format(points/total)
'Correct answers: 86.36%'

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

>>> '{:+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'

猜你喜欢

转载自www.cnblogs.com/zhengyionline/p/9187229.html