format格式化字符串方法相较于老版%格式方法的优点:
1.不需要理会数据类型的问题,在%方法中'%s'只能替代字符串类型.
2.单个参数可以多次输出,参数顺序可以不相同.
3.填充方式十分灵活,对齐方式十分强大.
4.官方推荐,%方法将会在后面的版本被淘汰.

format()方法的基本使用格式:
  <模板字符串>.format(<逗号分隔的参数>) 是由一系列的槽组成,用来控制修改字符串中嵌入值出现的位置,其基本思想是将format()方法的中的参数按照序号关系替换到的槽中.
槽用大括号{}表示,如果大括号中没有序号,则按照位置顺序替换:

>>> print('{}:计算机{}的CPU占用率为{}%'.format('2017-09-30', 'Python', 10))
2017-09-30:计算机Python的CPU占用率为10%
>>> print('{}:计算机{}的CPU占用率为{}%'.format('2017-09-30', 'Python', 10))
2017-09-30:计算机Python的CPU占用率为10%

如果大括号中指定了使用参数的序号,按照序号对应参数替换.参数从0开始编号:

>>> print('{1}:计算机{0}的CPU占用率为{2}%.'.format('python', '2017-09-30', 10))
2017-09-30:计算机python的CPU占用率为10%.
>>> print('{1}:计算机{0}的CPU占用率为{2}%.'.format('python', '2017-09-30', 10))
2017-09-30:计算机python的CPU占用率为10%.

除了通过序号来指定填充的参数外,还可以通过关键字参数,下标,字典的key和对象的属性来填充

>>> print('{date}:计算机{process}的CPU占用率为{per}%.'.format(date='2017-09-30', process='python', per=10))    # 关键字参数
2017-09-30:计算机python的CPU占用率为10%.
>>> print('I am {arg[0]}, I love {arg[1]}'.format(arg=arg))    # 下标
I am Liu, I love python

>>> person = {'name': 'Liu', 'age': 24, 'job': 'Pythoneer'}
>>> print('I am {person[name]}, {person[age]} years old, a {person[job]}.'.format(person=person))
I am Liu, 24 years old, a Pythoneer.

Class Person():
    def __init__(self):
        self.name, self.age, self.job = 'Liu', 24, 'Pythoneer'
>>> me = Person()
>>> print('I am {me.name}, {me.age} years old, a {me.job}'.format(me=me))
I am Liu, 24 years old, a Pythoneer.
>>> print('{date}:计算机{process}的CPU占用率为{per}%.'.format(date='2017-09-30', process='python', per=10))    # 关键字参数
2017-09-30:计算机python的CPU占用率为10%.
>>> print('I am {arg[0]}, I love {arg[1]}'.format(arg=arg))    # 下标
I am Liu, I love python

>>> person = {'name': 'Liu', 'age': 24, 'job': 'Pythoneer'}
>>> print('I am {person[name]}, {person[age]} years old, a {person[job]}.'.format(person=person))
I am Liu, 24 years old, a Pythoneer.

Class Person():
    def __init__(self):
        self.name, self.age, self.job = 'Liu', 24, 'Pythoneer'
>>> me = Person()
>>> print('I am {me.name}, {me.age} years old, a {me.job}'.format(me=me))
I am Liu, 24 years old, a Pythoneer.

format()方法中的槽除了包含参数序号,还可以包括格式控制符.此时,槽的内部样式如下:

   {:}

其中,用来控制参数显示时的格式.

PYTHON 变量在大括号 python中大括号的作用.format_浮点数


包括:,<.精度>6个字段,这些字段都是可选的,可以组合使用.

,和是3个相关字段.

  • :指当前槽的设定输出字符宽度,如果该槽对应的format()参数长度比设定值大,则会使用实际宽度.如果该值的实际位数小于指定宽度,则位数将被默认以空格补充.
  • :指参数在内输出是的对齐方式,分别使用<,>和=三个符号表示左对齐,右对齐和居中对齐.
  • :指内除了参数外的字符采用什么方式表示,默认采用空格.
>>> s = 'PYTHON'
>>> '{:30}'.format(s)
'PYTHON                        '
>>> '{:>30}'.format(s)
'                        PYTHON'
>>> '{:*^30}'.format(s)
'************PYTHON************'
>>> '{:-^30}'.format(s)
'------------PYTHON------------'
>>> '{:5}'.format(s)
'PYTHON'
>>> s = 'PYTHON'
>>> '{:30}'.format(s)
'PYTHON                        '
>>> '{:>30}'.format(s)
'                        PYTHON'
>>> '{:*^30}'.format(s)
'************PYTHON************'
>>> '{:-^30}'.format(s)
'------------PYTHON------------'
>>> '{:5}'.format(s)
'PYTHON'
  • 逗号,:中逗号(,)用于显示数字的千位分隔符
>>> '{:-^20,}'.format(123456789)
'----123,456,789-----'
>>>'{:-^20}'.format(123456789)    #对比输出
'-----123456789------'
>>> '{:-^20,}'.format(12345.67890)
'----12,345.6789-----'
>>> '{:-^20,}'.format(123456789)
'----123,456,789-----'
>>>'{:-^20}'.format(123456789)    #对比输出
'-----123456789------'
>>> '{:-^20,}'.format(12345.67890)
'----12,345.6789-----'
  • <.精度>:表示两个含义,有小数点(.)开头.对于浮点数,精度表示小数部分输出的有效位数.对于字符串,精度表示输出的最大长度.
>>> '{:.2f}'.format(12345.67890)
'12345.68'
>>> '{:H^20.3f}'.format(12345.67890)
'HHHHH12345.679HHHHHH'
>>> '{:.4}'.format('PYTHON')
'PYTH'
>>> '{:.2f}'.format(12345.67890)
'12345.68'
>>> '{:H^20.3f}'.format(12345.67890)
'HHHHH12345.679HHHHHH'
>>> '{:.4}'.format('PYTHON')
'PYTH'
  • :表示输出整数和浮点数类型的格式规则.对于整数类型,输出格式包括6中:
      b: 输出整数的二进制方式;
      c: 输出整数对应的Unicode字符;
      d: 输出整数的十进制方式;
      o: 输出整数的八进制方式;
      x:输出整数的小写十六进制方式;
      X:输出整数的大写十六进制方式;
>>> '{0:b}, {0:c}, {0:d}, {0:o}, {0:x}, {0:X}'.format(425)
'110101001, Ʃ, 425, 651, 1a9, 1A9'
>>> '{0:b}, {0:c}, {0:d}, {0:o}, {0:x}, {0:X}'.format(425)
'110101001, Ʃ, 425, 651, 1a9, 1A9'

 对于浮点数类型,输出格式包括4种:
  e: 输出浮点数对应的小写字母e的指数形式;
  E: 输出浮点数对应的大写字母E的指数形式;
  f: 输出浮点数的标准浮点形式;
  %: 输出浮点数的百分比形式;
浮点数输出是尽量是用<.精度>表示小数部分的宽度,有助于更好控制输出格式.

>>> '{0:e}, {0:E}, {0:f}, {0:%}'.format(3.14)
'3.140000e+00, 3.140000E+00, 3.140000, 314.000000%'
>>> '{0:.2e}, {0:.2E}, {0:.2f}, {0:.2%}'.format(3.14)
'3.14e+00, 3.14E+00, 3.14, 314.00%'
>>> '{0:e}, {0:E}, {0:f}, {0:%}'.format(3.14)
'3.140000e+00, 3.140000E+00, 3.140000, 314.000000%'
>>> '{0:.2e}, {0:.2E}, {0:.2f}, {0:.2%}'.format(3.14)
'3.14e+00, 3.14E+00, 3.14, 314.00%'
其他

转义{和}符号
使用{}对大括号进行转义

>>> 'hello {}, {{}}'.format('world')
'hello world, {}'
>>> 'hello {}, {{}}'.format('world')
'hello world, {}'

处理时间对象

>>> from datetime import datetime
>>> '{:%Y-%m-%d %X}'.format(datetime.now())
'2017-09-30 16:24:29'
>>> from datetime import datetime
>>> '{:%Y-%m-%d %X}'.format(datetime.now())
'2017-09-30 16:24:29'

参考官方文档中对时间的格式化字符.
一个快捷方法

>>> a, b = 'Life', 'Python'
>>> f'{a} is short, you need {b}'
'Life is short, you need Python'
>>> a, b = 'Life', 'Python'
>>> f'{a} is short, you need {b}'
'Life is short, you need Python'