1

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

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

4 回答 4

4

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

于 2009-10-22T08:51:24.130 回答
4

稍微偏离主题,但您可以避免在totusing上执行显式添加enumerate

for tot, p in enumerate(players, start=1):
    print '...'
于 2009-10-22T09:13:05.713 回答
3

或者,如果您使用 python 2.6,您可以使用字符串的格式方法:

这定义了一个值字典,并将它们用于 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'
于 2009-10-22T09:11:29.237 回答
2

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

print '%2d' % tot + ': %(nick)-15s \t (%(x)d|%(y)d) \t was: %(oldnick)15s' % p
于 2009-10-22T09:08:09.820 回答