网络编程
位置:首页>> 网络编程>> Python编程>> Python利用format函数实现对齐打印(左对齐、右对齐与居中对齐)

Python利用format函数实现对齐打印(左对齐、右对齐与居中对齐)

作者:暖暖Immer  发布时间:2021-07-30 05:16:16 

标签:python,format,对齐

forma格式化的用法

format函数可以接受不限个参数,位置可以不按顺序。

基本语法是通过{ }和:来代替c语言的%。

>>> a="名字是:{0},年龄是:{1}"
>>> a.format("煮雨",18)
'名字是:煮雨,年龄是:18'

{0},{1}代表的占位符,数字占位符要注意顺序。

>>> c="名字是:{name},年龄是:{age}"
>>> c.format(age=19,name='煮雨')
'名字是:煮雨,年龄是:19'

用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)
输出结果如下所示:

*        
***      
*****    
*******  
*********

来源:https://blog.csdn.net/weixin_44630991/article/details/86767601

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com