format()方法的基本使用

来源:互联网 发布:闾丘露薇 知乎 编辑:程序博客网 时间:2024/06/05 14:50

1,使用格式


<模板字符串>.format(参数)

>>> "{},{}".format('python','大法好')'python,大法好'

2,格式控制


“{<参数序号>:<填充><对齐><宽度><,千位分隔符><精度><类型>}”

1. 填充

>>> s='python'>>> "{:*>30}".format(s)#用*填充'************************python'

2. 对齐

>>> s='python'>>> "{:*>30}".format(s)#>右对齐<左对齐^居中对齐'************************python'

3. 宽度

s=’python’
“{:*>30}”.format(s)#宽度30
‘************************python’

4. 千位分隔符

>>> "{:,.2f}".format(a)'12,345.68'

5. 精度

. 精度:浮点数保留位数|字符串保留位数

>>> "{:,.2f}".format(a)'12,345.68'

6. 类型

>>> "{:,.2f}".format(a)'12,345.68'