在 python 中,可用 rjust() 、 ljust() 和 center() 方法分别实现文本右对齐、左对齐以及居中对齐功能。

它们的第一个参数是一个整数,表示填充后的总长度。不足的部分,使用空格(默认)来填充。
print('如何搭建数据中台'.rjust(10)+',')
print('如何搭建数据中台'.rjust(20)+',')
print('如何搭建数据中台'.ljust(20)+',')
运行结果:

它们的第二个参数表示需要填充的字符(可选), 默认为空格字符。
print('如何搭建数据中台'.ljust(20,'*')+',')
运行结果:
center() 使用方法与 rjust() 、 ljust() 类似:
print('如何搭建数据中台'.center(20)+',')
print('如何搭建数据中台'.center(20,'*')+',')
运行结果:

这些方法很适合打印表格式数据, 比如购物小票:
def print_shopping_list(data, left_width, right_width):
'''
打印购物小票
:param data:
:param left_width: 左列宽度
:param right_width: 右列宽度
:return:
'''
print('购物小票'.center(left_width + right_width, '-'))
for k, v in data.items():
print(k.ljust(left_width, '.') + str(v).rjust(right_width))
data = {'慢跑鞋': 128, '励志故事': 29.8, '日程本': 19.9}
print_shopping_list(data, 15, 8)
print_shopping_list(data, 25, 18)
运行结果:

是不是很简单呀 O(∩_∩)O哈哈~
以上就是良许教程网为各位朋友分享的Linu系统相关内容。想要了解更多Linux相关知识记得关注公众号“良许Linux”,或扫描下方二维码进行关注,更多干货等着你 !
