Python--⽤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):
python格式化输出formattail = "*"*(2*n-1)
width = len(tail)
for i in range(1,2*n,2):
print("{:<{}}".format("*"*i,width))
show(5)
输出结果如下所⽰:
*
***
*****
*******
*********

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。