python lable 居中 python中居中函数

您所在的位置:网站首页 python中center怎么用 python lable 居中 python中居中函数

python lable 居中 python中居中函数

2023-06-20 00:13| 来源: 网络整理| 查看: 265

1  居中输出    需要使用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中居中函数_字符串_02

 

 

 

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

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

 

 

python lable 居中 python中居中函数_可选参数_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中居中函数_可选参数_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中居中函数_python lable 居中_11

 

 

python lable 居中 python中居中函数_可选参数_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("{:


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3