居中输出    需要使用center函数

使用center函数,需要str类型的数据。
width参数:长度,需要填一个int类型的参数
fillchar参数:两边填充的字符,需要一个str类型的参数(可以为空格,但不能为空)

 

S: str = 'one people'
print(S.center(10, '*'))
print(S.center(20, '*'))
print(S.center(60, '*'))

 

python lable 居中 python中居中函数_python lable 居中

 

 

 

python lable 居中 python中居中函数_占位符_02

 

 

 

python lable 居中 python中居中函数_占位符_03


print('开始打印'.center(66,'-'))
 
print('打印完毕'.center(66,'-'))

 

 

python lable 居中 python中居中函数_python lable 居中_04

 

 

 

String.ljust(width[, fillchar]) 
String.rjust(width[, fillchar]) 
String.center(width[, fillchar])

String: 待填充字符串
width: 总长度
fillchar: 可选参数 默认空格


2 通过使用ljust(),center(),rjust()函数来实现输入字符串的左右对齐,居中,右对齐等操作;

 方法一:(函数不带参数,则默认以空格填充,注意:文字与空格总字符数等于输入的数字)

 

python lable 居中 python中居中函数_可选参数_05

 

 

 

python lable 居中 python中居中函数_可选参数_06

 

 方法二:(函数带参数,则以参数作为填充字符)

 

python lable 居中 python中居中函数_python lable 居中_07

 

 

python lable 居中 python中居中函数_字符串_08

 

String: 待填充字符串
width: 总长度
fillchar: 可选参数 默认空格

python lable 居中 python中居中函数_字符串_09

 

 

python lable 居中 python中居中函数_可选参数_10

 

 

forma格式化的用法

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

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

>>> a="名字是:{0},年龄是:{1}"

>>> a.format("煮雨",18)

'名字是:煮雨,年龄是:18'

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

 

>>> c="名字是:{name},年龄是:{age}"

>>> c.format(age=19,name='煮雨')

'名字是:煮雨,年龄是:19'

 

 

 

用format函数实现对齐打印

  • 居中对齐 (:^)
  • 靠左对齐 (:<)
  • 靠右对齐 (:>)

python lable 居中 python中居中函数_可选参数_11

 

 

python lable 居中 python中居中函数_python lable 居中_12

 

 

居中对齐示例

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,作为对齐打印基准

右对齐示例

def show(n):
      tail = "*"*(2*n-1)
      width = len(tail)
      for i in range(1,2*n,2):
            print("{:>{}}".format("*"*i,width))

左对齐示例

def show(n):
      tail = "*"*(2*n-1)
      width = len(tail)
      for i in range(1,2*n,2):
           print("{:<{}}".format("*"*i,width))