Python 深入学习str.format(...)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chenbetter1996/article/details/82899858

str.format(...)是个很好用的字符串格式化函数,用于print输出很方便

1. str没被赋值

>>> print(str.format("保留两位小数:{0:3.2f}", 91.35465))
保留两位小数:91.35

>>> print(str.format("保留两位小数:{0:4.2f}", 91.35465))
保留两位小数:91.35

>>> print(str.format("保留两位小数:{0:6.2f}", 91.35465))
保留两位小数: 91.35

>>> print(str.format("保留两位小数:{0:<3.2f}", 91.35465))
保留两位小数:91.35 

>>> print(str.format("保留两位小数:{0:<6.2f}", 91.35465))
保留两位小数:91.35 

>>> print(str.format("保留两位小数:{0:>3.2f}", 91.35465))
保留两位小数:91.35

>>> print(str.format("保留两位小数:{0:>6.2f}", 91.35465))
保留两位小数: 91.35

str.format("xxx:"{a:b.c}", xxxx))   

""" 

      a表示第几个参数(从0开始),

      b表示输出的参数占几位,多的左边补空格(小于正常位数的以正常位数为准)

      c表示保留的小数位数,浮点后面还需添加f

      '<'小于号如({0:<6.2f}) 如果够长(c > 参数长度),右侧填补空格(空格数为c-参数长度)

     ‘>'大于号表示如果够长左侧填补空格 [ 和小于号可以根据开口方向记忆】

"""

2. str被赋值了

>>> print("{0}.....{1}".format("hello","world"))
hello.....world

>>> print("{0:6}.....{1}".format("hello","world"))
hello .....world

>>> print("{0:6}.....{1:8}".format("hello","world"))
hello .....world   

>>> print("{0:6}.....{1:>8}".format("hello","world"))
hello .....   world

>>> print("{0:<6}.....{1:>8}".format("hello","world"))
hello .....   world

>>> print("{0:>6}.....{1:>8}".format("hello","world"))
 hello.....   world

格式化部分从刚刚的 str.forma(格式部分,参数),跑到了str上,format只需要管理参数。

和上面一样, ’<'向右边补空格, ‘>'向左边不空格。

总结:如果了解输出结果,尽量指明 ’>‘, ’<‘, 默认输出不空格不易确定。

猜你喜欢

转载自blog.csdn.net/chenbetter1996/article/details/82899858