python怎么输出文字_如何用Python打印“漂亮”字符串输出

class TablePrinter(object):

"Print a list of dicts as a table"

def __init__(self, fmt, sep=' ', ul=None):

"""

@param fmt: list of tuple(heading, key, width)

heading: str, column label

key: dictionary key to value to print

width: int, column width in chars

@param sep: string, separation between columns

@param ul: string, character to underline column label, or None for no underlining

"""

super(TablePrinter,self).__init__()

self.fmt = str(sep).join('{lb}{0}:{1}{rb}'.format(key, width, lb='{', rb='}') for heading,key,width in fmt)

self.head = {key:heading for heading,key,width in fmt}

self.ul = {key:str(ul)*width for heading,key,width in fmt} if ul else None

self.width = {key:width for heading,key,width in fmt}

def row(self, data):

return self.fmt.format(**{ k:str(data.get(k,''))[:w] for k,w in self.width.iteritems() })

def __call__(self, dataList):

_r = self.row

res = [_r(data) for data in dataList]

res.insert(0, _r(self.head))

if self.ul:

res.insert(1, _r(self.ul))

return '\n'.join(res)

使用中:data = [

{'classid':'foo', 'dept':'bar', 'coursenum':'foo', 'area':'bar', 'title':'foo'},

{'classid':'yoo', 'dept':'hat', 'coursenum':'yoo', 'area':'bar', 'title':'hat'},

{'classid':'yoo'*9, 'dept':'hat'*9, 'coursenum':'yoo'*9, 'area':'bar'*9, 'title':'hathat'*9}

]

fmt = [

('ClassID', 'classid', 11),

('Dept', 'dept', 8),

('Course Number', 'coursenum', 20),

('Area', 'area', 8),

('Title', 'title', 30)

]

print( TablePrinter(fmt, ul='=')(data) )

产生ClassID Dept Course Number Area Title

=========== ======== ==================== ======== ==============================

foo bar foo bar foo

yoo hat yoo bar hat

yooyooyooyo hathatha yooyooyooyooyooyooyo barbarba hathathathathathathathathathat

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值