2009-10-22 63 views
1

我使用这个简单的功能:Python化的方式来打印表

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 

回答

2

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

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

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

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' 
+0

**值是什么意思?我只在参数声明(函数/方法的声明)中看到了'**'。 – 2009-10-22 09:36:01

+1

@Andrea:它将字典的键/值对作为一系列命名参数传递给函数。所以,如果'd = {'a':1,'b':2}',那么'f(** d)'相当于'f(a = 1,b = 1)'。 – Stephan202 2009-10-22 09:41:51

+0

我不知道,非常感谢! – 2009-10-22 09:43:12

4

稍微偏离主题,但你可以尽量避免使用01 tot上进行明确的另外:

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