格式化输出format
Python学习笔记
用format函数实现对齐打印
居中对齐 (:^)
靠左对齐 (:<)
靠右对齐 (:>)
居中对齐示例
def show(n):
tail = "*"*(2*n-1) #最底下一行显示出(2*n-1)个星号
width = len(tail) #计算星号所在行的宽度,作为其他行的对齐基准
for i in range(1,2*n,2):
print("{:^{}}".format("*"*i,width))
format函数读取变量时候由外向内:
{ :^{ } },括号读取变量=="*"*i==
{ :^ { } } ,居中对齐
{ :^ { } } ,最内层括号读取变量width,作为对齐打印基准
show(5)
输出结果如下所示:
*
***
*****
*******
********* #tail变量,显示出9个星号(n = 5)
右对齐示例
def show(n):
tail = "*"*(2*n-1)
width = len(tail)
for i in range(1,2*n,2):
print("{:>{}}".format("*"*i,width))
show(5)
输出结果如下所示:
*
***
*****
*******
*********
左对齐示例
def show(n):
tail = "*"*(2*n-1)
width = len(tail)
for i in range(1,2*n,2):
print("{:<{}}".format("*"*i,width))
show(5)
输出结果如下所示:
*
***
*****
*******
*********