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

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
有帮助吗?

解决方案

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

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

其他提示

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

稍微偏离主题,但您可以避免使用 tot 执行显式添加=“nofollow noreferrer”> 枚举

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

或者如果你使用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'
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top