python上下对齐_Python间距和对齐字符串

复活另一个主题,但这可能对某些人派上用场。

借鉴[https://pyformat.info]的启发,您可以构建一种方法来获取目录[TOC]样式的打印输出。

# Define parameters

Location = '10-10-10-10'

Revision = 1

District = 'Tower'

MyDate = 'May 16, 2012'

MyUser = 'LOD'

MyTime = '10:15'

# This is just one way to arrange the data

data = [

['Location: '+Location, 'Revision:'+str(Revision)],

['District: '+District, 'Date: '+MyDate],

['User: '+MyUser,'Time: '+MyTime]

]

# The 'Table of Content' [TOC] style print function

def print_table_line(key,val,space_char,val_loc):

# key: This would be the TOC item equivalent

# val: This would be the TOC page number equivalent

# space_char: This is the spacing character between key and val (often a dot for a TOC), must be >= 5

# val_loc: This is the location in the string where the first character of val would be located

val_loc = max(5,val_loc)

if (val_loc <= len(key)):

# if val_loc is within the space of key, truncate key and

cut_str = '{:.'+str(val_loc-4)+'}'

key = cut_str.format(key)+'...'+space_char

space_str = '{:'+space_char+'>'+str(val_loc-len(key)+len(str(val)))+'}'

print(key+space_str.format(str(val)))

# Examples

for d in data:

print_table_line(d[0],d[1],' ',30)

print('\n')

for d in data:

print_table_line(d[0],d[1],'_',25)

print('\n')

for d in data:

print_table_line(d[0],d[1],' ',20)

结果输出如下:

Location: 10-10-10-10 Revision:1

District: Tower Date: May 16, 2012

User: LOD Time: 10:15

Location: 10-10-10-10____Revision:1

District: Tower__________Date: May 16, 2012

User: LOD________________Time: 10:15

Location: 10-10-... Revision:1

District: Tower Date: May 16, 2012

User: LOD Time: 10:15

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值