Pythonic方式打印表

时间:2009-10-22 08:48:49

标签: printing python string-formatting

我正在使用这个简单的功能:

def print_players(players):
    tot = 1
    for p in players:
        print '%2d: %15s \t (%d|%d) \t was: %s' % (tot, p['nick'], p['x'], p['y'], p['oldnick'])
        tot += 1

我假设刻痕不超过15个字符 我想保持每个“列”对齐,是否有一些语法糖允许我做同样但保持昵称列左对齐而不是右对齐,而不打破右边的列?

等效的,更丑陋的代码是:

def print_players(players):
    tot = 1
    for p in players:
        print '%2d: %s \t (%d|%d) \t was: %s' % (tot, p['nick']+' '*(15-len(p['nick'])), p['x'], p['y'], p['oldnick'])
        tot += 1

感谢所有人,这是最终版本:

def print_players(players):
    for tot, p in enumerate(players, start=1):
        print '%2d:'%tot, '%(nick)-12s (%(x)d|%(y)d) \t was %(oldnick)s'%p

4 个答案:

答案 0 :(得分:4)

要左对齐而不是右对齐,请使用%-15s代替%15s

答案 1 :(得分:4)

稍微偏离主题,但您可以避免使用enumeratetot上执行明确添加:

for tot, p in enumerate(players, start=1):
    print '...'

答案 2 :(得分:3)

或者如果你使用python 2.6,你可以使用字符串的format方法:

这定义了一个值字典,并将它们用于dipslay:

>>> values = {'total':93, 'name':'john', 'x':33, 'y':993, 'oldname':'rodger'}
>>> '{total:2}: {name:15} \t ({x}|{y}\t was: {oldname}'.format(**values)
'93: john            \t (33|993\t was: rodger'

答案 3 :(得分:2)

看到p似乎是一个字典,怎么样:

print '%2d' % tot + ': %(nick)-15s \t (%(x)d|%(y)d) \t was: %(oldnick)15s' % p
相关问题