Python3中除了能使用格式化输出外
>>> print("%s" %"Python programing")
Python programing
还提供了format方法
print("{[对应位置] : [填充符(默认用空格)][对齐方式 < 左对齐;>右对齐;^ 居中对齐][所占位数] [. f 小数点位数] }")
- 常用顺序为: : 后 填充符 、 对齐方式 、 占位 、 输出小数位数
例如:
>>> print("{:.3f}".format(12.369854))
12.370
填充与对齐:
>>> print("{:-<20.2f}".format(3.1415926))
3.14----------------
>>> print("{:->20.2f}".format(3.1415926))
----------------3.14
>>> print("{:-^20.2f}".format(3.1415926))
--------3.14--------
- format输出中可以嵌套槽,用来表示宽度、填充等含义
>>> print("{0:{1}^{2}.2f}".format(3.1415926,"*",20))
********3.14********
- 这里采用了位置参数来填充 {} 里的内容,还可以利用其他方法
>>> print("Hello {0},I am {1},this is a new {0}".format("World" , "Python"))
Hello World,I am Python,this is a new World
- 除了采用位置参数,还可以采用关键字参数
>>> name_0 = "World"
>>> name_1 = "Python"
>>> print("Hello {key_0},I am {key_1},this is a new {key_0}".format(key_0 = name_0, key_1 = name_1))
Hello World,I am Python,this is a new World
- 可以通过列表传递给位置参数,进行切片输出
>>> name = ["World", "Python"]
>>> print("Hello {key[0]},I am {key[1]},this is a new {key[0]}".format(key = name))
Hello World,I am Python,this is a new World
- 这个参数key也可以是字典类型,通过键值对的方式传递数据
>>> Dict = {"obj":"World","name":"Python"}
>>> print("Hello {key[obj]},I am {key[name]},this is a new {key[obj]}".format(key = Dict))
Hello World,I am Python,this is a new World
- 这个参数key也可以是一个类
>>> class Name():
def __init__(self,obj = "World", name = "Python"):
self.obj = obj
self.name = name
>>> name = Name()
>>> print("Hello {key.obj},I am {key.name},this is a new {key.obj}".format(key = name))
Hello World,I am Python,this is a new World
对上述方法,对于可变的输出,这几种方法提供了一些思路!