借鉴两篇优秀的博文:
https://www.cnblogs.com/lovejh/p/9201219.html 作者:lovejh
https://blog.youkuaiyun.com/i_chaoren/article/details/77922939 作者:i_chaoren
1.简单运用
1、基本用法
(1)不带编号,即“{}”
(2)带数字编号,可调换顺序,即“{0}”、”{1}”、“{2}”
(3)带关键字,即“{a}”、“{tom}”
In [1]: print('{} {}'.format('hello','world')) # 不带字段
hello world
In [2]: print('{0} {1}'.format('hello','world')) # 带数字编号
hello world
In [3]: print('{0} {1} {0}'.format('hello','world')) # 打乱顺序
hello world hello
In [4]: print('{1} {1} {0}'.format('hello','world'))
world world hello
In [5]: print('{a} {tom} {a}'.format(tom='hello',a='world')) # 带关键字
world hello world
字符串类型格式化采用format()方法,基本使用格式是:
<模板字符串>.format(<逗号分隔的参数>)
调用format()方法后会返回一个新的字符串,参数从0 开始编号
2. 格式控制信息
format()方法中<模板字符串>的槽除了包括参数序号,还可以包括格式控制信息。此时,槽的内部样式如下:
{<参数序号>: <格式控制标记>}
其中,<格式控制标记>用来控制参数显示时的格式,包括:<填充><对齐><宽度>,<.精度><类型>6 个字段,这些字段都是可选的,可以组合使用,逐一介绍如下。
1. 填充
指<宽度>内除了参数外的字符采用什么方式表示,默认采用空格,可以通过<填充>更换。
2. 对齐
指参数在<宽度>内输出时的对齐方式,分别使用<、>和^三个符号表示左对齐、右对齐和居中对齐。
3. 宽度
指当前槽的设定输出字符宽度,如果该槽对应的format()参数长度比<宽度>设定值大,则使用参数实际长度。如果该值的实际位数小于指定宽度,则位数将被默认以空格字符补充。
例子:
In [4]: ss = 'python'
In [5]: '{0:20}'.format(ss)
Out