Skip to main content
 首页 » 编程设计

printing之打印表格的 Pythonic 方式

2025年05月04日9kuangbin

我正在使用这个简单的函数:

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 

请您参考如下方法:

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